Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have a following table , table1 ``` date value ------------------------- 2015-01-01 0 2015-01-02 0 2015-01-03 0 2015-01-04 0 ``` And have a table2 ``` datestart dateend value ------------------------------------- 2015-01-02 2015-01-03 1 ``` I would like...
You can use a left join like this: ``` select table1.date, coalesce(table2.value,0) Value from table1 left join table2 on table1.date between table2.startdate and table2.enddate order by 1 ``` Although it'll get messy if you have overlapping dates in table 2. This may not be what you intended, but if you wanted to s...
You don't need a cross join, but a left join: ``` SELECT table1.date, table2.value FROM table1 LEFT JOIN table2 ON table1.date BETWEEN table2.startdate AND table2.enddate ```
Cross joining sql tables by date
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "cross-join", "" ]
I have two tables, `Stock` and `Warehouse`. I need to get the Items which are available in all Warehouses. Here an example: ``` Stock Table: ItemID WarehouseID ItemAmount ------------------------------------------- 1043 1 20 1043 2 2 1043 ...
``` select itemid from stock group by itemid having count(distinct warehouseid) = (select count(*) from warehouse); ``` SQLFiddle: <http://sqlfiddle.com/#!15/e4273/1> If the stock table may also contain items with an amount = 0 you need to add a where clause: ``` select itemid from stock where itemamount > 0 group b...
You could also use this "double negative" query using `NOT EXISTS`: ``` SELECT DISTINCT s.ItemID FROM StockTable s WHERE NOT EXISTS ( SELECT 1 FROM Warehouse w WHERE NOT EXISTS(SELECT 1 FROM StockTable s2 WHERE w.WarehouseID = s2.WarehouseID AND s.ItemID = s2.ItemI...
SQL, Check if Rows are in another Table
[ "", "sql", "sql-server", "ssms", "" ]
i want to do running total of amount based on debit and credit amt in following table there is one column drcr in which 'c' stand for credit and 'd' for debit and it should be done with grouping name also. i want following output using sql server query ``` Name amt drcr Total | 'abc'| 1| 'c'|1 | | 'abc'|...
Try this: (**Improved**) ``` SELECT intId, varName, decAmt, charCrDr, SUM(CASE WHEN charCrDr = 'c' THEN decAmt ELSE decAmt * -1 END ) OVER (PARTITION BY varName ORDER BY intId) As decTotal FROM #Temp; ``` [see fiddle here](http://sqlfiddle.com/#!3/...
HI Navnit This is simple you use 'Sum( case when charCrDr = 'c' Then decAmt else -decAmt end) over( order by intId)` in your statement . ``` select *,Sum( case when charCrDr = 'c' Then decAmt else -1*decAmt end) over( PARTITION BY varName ORDER BY intId) as Total from #temp t ```
sql server running total with condition with debit credit balance
[ "", "sql", "sql-server", "" ]
This the sample of my data: ``` +----+---+----+----+----+----+----+-------------+------------+-------------+ | ID | C | C1 | C2 | C3 | C4 | C5 | EndingPoint | TransferID | Transferred | +----+---+----+----+----+----+----+-------------+------------+-------------+ | 1 | A | A | | | | | B | 1 ...
You can implement the logic using a bunch of `union all` statements: ``` select c1 as frompt, endingpoint as topt, transferred from t where transferred = 1 union all select c1 as frompt, c2 as topt, transferred from t where transferred = 2 union all select c2 as frompt, endingpoint as topt, transferred from t where tr...
You can unpivot those C1-EndingPoint columns and then use the Lead function and order by the C1 to EndingPoint column names (which happen to be in correct order)... <http://sqlfiddle.com/#!3/61e519/2> ``` select * from ( select ID, [From] = pt, [To] = Lead(pt, 1) over(partition by Id order...
TSQL query based on IF?
[ "", "sql", "sql-server", "t-sql", "" ]
I show you an example of what I need. Table with these columns and data for example: ``` id | mapname | username | score ----|-----------|-----------|-------- 1 | mid_town | carolina | 5 2 | mid_town | rupert | 10 3 | id_room | carolina | 7 4 | mid_town | mordor | 14 5 | id_room | intel ...
A friend answered it: ``` SELECT t1.username, COUNT(t3.var2) as var1 FROM data AS t1 JOIN (SELECT t2.mapname, MAX(t2.score) as var2 FROM data AS t2 GROUP BY mapname) AS t3 ON t1.mapname = t3.mapname AND t1.score = t3.var2 GROUP BY t1.username ORDER BY var1 DESC; ```
Try this: ``` select username, score from `table` where (mapname,score) in (select mapname, max(score) from `table` group by mapname) ```
Get the best from map and count
[ "", "mysql", "sql", "" ]
Is there a way to select all days between two timestamps. Say I have 2 timestamps 2/1/2015 and 2/28/2015 Is there a way to SELECT all days between the too Output: ``` days -------- 2/1/2015 | 2/2/2015 | 2/3/2015 | ... 2/26/2015 | 2/27/2015 | 2/28/2015 | ``` Edit: I am trying to count some records that were crea...
You can use [generate\_series](http://www.postgresql.org/docs/9.4/static/functions-srf.html) to generate all dates between your two dates, and do a join with your table using the timestamp column: ``` SELECT a_date, count(days) FROM generate_series('2015-01-01'::timestamp, '2015-03-31', '1 day') a_date left outer j...
Sure. How about: `SELECT * FROM table WHERE days>='2015-02-01' AND days<='2015-02-28'`
SELECT all date interval from timestamp to timestamp
[ "", "sql", "postgresql", "date", "" ]
I am trying to add max and min to the query below: ``` SELECT category, COUNT(distinct VIN) COUNT FROM stock group by category order by category ASC ``` The desired results are to show the category with the most items in the count and to show the category with the least items in the count. CURRENT OUTPUT: ``` CATEG...
``` select count(VIN), Category from STOCK having count(VIN)=(select max(count(VIN)) from STOCK group by Category ) OR count(VIN)=(select min(count(VIN)) from STOCK group by Category ) group by Category; ```
The best way I can think of doing this is to union two queries to find the max and min counts like below: ``` Select category, CNT FROM (SELECT category, COUNT(distinct VIN) CNT FROM stock group by category Order by CNT asc) a where RowNum = 1 UNION Select category, CNT FROM (SELECT category, COUNT(distinct VIN) CNT F...
Adding max(count) and min(count) to query
[ "", "sql", "oracle11g", "max", "min", "" ]
I need help on generating a Oracle SQL query... The thing is that I have the following table: ``` COL1 COL2 COL3 ---------------- 1 A XXXX 1 B LLLL 1 F TTTT 5 B GGGG 5 C VVVV 7 D FFFF 7 E AAAA 7 S SSSS ``` The thing is that I need a query to show all ...
You could use **COUNT() OVER()** analytic function along with **DISTINCT**. For example, ``` SQL> SELECT t1.*, 2 COUNT(distinct col1) OVER() DIFF_COUNT 3 FROM t1; COL1 C COL3 DIFF_COUNT ---------- - ---- ---------- 1 A XXXX 3 1 B LLLL 3 1 F TTTT ...
The simplest way is: ``` select col1, col2, col3, count(distinct col1) over() cnt from test ``` [SQLFiddle demo](http://sqlfiddle.com/#!4/7511d/1)
Building query: Distinct count
[ "", "sql", "oracle", "count", "group-by", "" ]
``` SELECT * FROM MY_TABLE; CLOUMN_NAME 1st 2nd 3rd ``` Am getting the output when I run this query. I need to have a ***default value for 'Please Select' as first row always*** even column holds the empty or null value of the result set. Exptected Result ``` CLOUMN_NAME Please Select 1st 2nd 3rd ``` Thanks in ad...
``` select 'please select' col_name union all select col_name::text FROM MY_TABLE; ``` --- Edit : as per [this](https://stackoverflow.com/questions/30369423/set-default-first-row-in-sql-in-postgres/30371954?noredirect=1#comment48950849_30371954) comment In your case you need to use `order by` in **second** *select s...
Try to use `union all` as below ``` SELECT 'Please Select' as CLOUMN_NAME union all SELECT cast(CLOUMN_NAME as varchar) FROM MY_TABLE; ``` I'm not sure what type is `CLOUMN_NAME` but should be `string` type because in first query we return this type.
Set default first row in sql in postgres
[ "", "sql", "postgresql", "" ]
I have a query that I am running in a stored procedure. However, is produces the error: ``` Incorrect syntax near 'CHEQUE' ``` The query is: ``` SELECT @QUERY1 = 'UPDATE [dbo].[ATAB] SET PAYMCODE='CHQ' WHERE RATE=1' ``` How do I specify this string 'CHQ' without getting an error?
You have to escape your single quotes. ``` SELECT @QUERY1 = 'UPDATE [dbo].[ATAB] SET PAYMCODE=''CHQ'' WHERE RATE=1' ```
When specifying a string literal within a dynamic SQL string you have to escape the single quotation with another single quotation (ex: `''`, not `"` which is double quotation) So the query will be like this: ``` SELECT @QUERY1 = 'UPDATE [dbo].[ATAB] SET PAYMCODE=''CHQ'' WHERE RATE=1' ``` This will translate it to: ...
Specify String In Stored procedure query
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have a table like so [filenameAndDate][DateCreated] the first column looks like this "myvideo/12.12.2012" and the second column is empty How would I write a sql query to extract the date from [filenameAndDate] and place it into the [DateCreated] column
``` UPDATE [dbo].[FileNames] SET [DateCreated] = Convert(Date, SUBSTRING(FileNameAndDate, CHARINDEX('/', FileNameAndDate, 0) + 1, LEN(fileNameAndDate))) ``` *this is for MSSQL*
You can try this, mate: ``` UPDATE <your_table> SET DateCreated = RIGHT(filenameAndDate, 10) WHERE filenameAndDate = 'myvideo/12.12.2012'; ``` Suggestion: * Maybe you can *organize* your table in a way it may not hurt an application based on the content of a field. * Another one is the format of the date you'l...
Extracting substring from one coloumn and placing it into another SQL
[ "", "mysql", "sql", "" ]
This is a little complicated but I simplified it as much as I can. I have a contacts table that contains first name last name, etc. It also contains 2 columns indicating the group (src) the contact is associated with and it's id in that group (uID). I'm trying to do a contact search. So if I'm looking for mike, it's si...
Try: ``` SELECT c.contactID, CASE c.src WHEN 0 THEN (SELECT tbl.code FROM CSA.dbo.Clients tbl WHERE clientID=c.uID) WHEN 1 THEN (SELECT tbl.scac FROM CSA.dbo.Carriers tbl WHERE carrierID=c.uID) WHEN 2 THEN (SELECT tbl.code FROM codeBase tbl WHERE cID=c.uID) END as code, fName+' '+lna...
You can use a [common table expression](https://technet.microsoft.com/en-us/library/ms190766%28v=sql.105%29.aspx "common table expression") to get your result including the `code` column and then filter on it. ``` WITH CTE AS ( SELECT c.contactID, CASE c.src WHEN 0 THEN (SELECT tbl.code FROM CSA.dbo....
Select column with Case and using WHERE on that column
[ "", "sql", "sql-server", "" ]
Please let me know if there's a query for this case: I want to delete multiple rows based on spesific column ``` id | date | user | item | material | Text | Description | ------+------------+-----------+-------+--------------------+------+-------------+ 12345 | 31.03.2015 | Starbucks | 00010 |...
Yes you can. You need to group the results to keep and then use that table with a join to connect to the master table. Here's one way to only keep the records with the max id and no null ids ``` Delete from [Table] From [Table] left join ( Select MAX(ID) as ID from [Table] Where ID is not Null group b...
You can also use [Window functions](https://msdn.microsoft.com/en-us/library/ms189798.aspx) within a [CTE](https://technet.microsoft.com/en-us/library/ms190766%28v=sql.105%29.aspx) **Sample data** ``` DECLARE @tbl TABLE (id INT, [date] VARCHAR(10) ,[user] VARCHAR(20), item VARCHAR(10), material VARCHAR(50), [Text] VA...
How to delete rows that has multiple values and pick only 1 row
[ "", "sql", "sql-server", "database", "" ]
I have a data set like below, ``` Lot Size Reported QTY Qty Balance 150 100 150 100 150 80 150 80 150 5 ``` The Qty Balance needs to calculated as follows, ``` Row 1 = Lot Size - Reported Qty (row1) => 150-100 = 50 Ro...
[SQL Fiddle](http://sqlfiddle.com/#!4/8b32d5/1) **Oracle 11g R2 Schema Setup**: ``` CREATE TABLE lots ( Lot_Size, Reported_QTY ) AS SELECT 150, 100 FROM DUAL UNION ALL SELECT 150, 100 FROM DUAL UNION ALL SELECT 150, 80 FROM DUAL UNION ALL SELECT 150, 80 FROM DUAL UNION ALL SELECT 150, 5 FROM DUAL; ``` ...
As @Boneist suggested, you need to use **LAG() OVER()** analytic function. You just need to do one more task to handle the first row which will be NULL, using **CASE** you could make it work. **Test case** ``` SQL> WITH data AS 2 ( SELECT t.*, lag(reported_qty) OVER(ORDER BY NULL) rn FROM t 3 ) 4 SELECT...
How do i do running totals from second column
[ "", "sql", "oracle", "lag", "window-functions", "analytic-functions", "" ]
i need some help here. I am trying to extract the data through SQL in excel having the join query but i am getting the debug error while running through below code.. ``` recset.Open strSQL, con, adOpenDynamic, adLockOptimistic ``` > Error - Runtime error -2147467259 Below is the code.....Please help :confused: ``` ...
Finally i had solved the error.....actually in a coding where i have given parameter in which the quotes was given the problem...i.e. Previously i was running the query with below code, ``` strSQL & " AND [ORACLE_ITEM_CODE]='" ``` Just beacause there was the quote > `"["` ...ws getting that error. But after remov...
Where you have code like ``` "WHERE 1=1" & _ "AND A.CREATED_BY = B.USER_ID" & _ ``` It will be rendered ``` "WHERE 1=1AND A.CREATED_BY = B.USER_ID" ``` i.e. No space between the `1=1` and `AND` Try putting a space before closing quotes on each line: ``` "WHERE 1=1 " & _ "AND A.CREATED_BY = B.USER_ID " & _ ```
Getting an error while joining the SQL tables through excel VBA
[ "", "sql", "excel", "ms-access", "vba", "" ]
I am hoping someone can help me. I'm not that good with SQL. I've looked at countless other posts and just can't figure it out. I have the following data and need to get the most recent date. That would be 09/01/1993. ``` 524 | David | NULL | 1991 | 01 | H | 1991-07-01 00:00:00.000 524 | David | NULL | 1992 | 01 | H ...
You probably want the highest date, but all other columns, too. You need a Windowed Aggregate Function for this: ``` SELECT * FROM ( SELECT student_crs_hist.id_num, name_format_view.last_first_middle_suf, year_term_table.pesc_session_type, student_crs_hist.yr_cde, stud...
``` SELECT student_crs_hist.id_num, name_format_view.last_first_middle_suf, year_term_table.pesc_session_type, student_crs_hist.yr_cde, student_crs_hist.trm_cde, student_crs_hist.TRANSACTION_STS, year_term_table.TRM_BEGIN_DTE FROM student_crs_hist, name_format_v...
SQL Get Most Recent Date
[ "", "sql", "sql-server", "max", "" ]
I have a table something like this ``` NAME TIME IsTrue A 15-05-2015 02:00 0 B 15-05-2015 03:00 1 C 15-05-2015 06:00 0 D 15-05-2015 13:00 0 E 15-05-2015 23:00 0 F 16-05-2015 04:00 0 E 16-05-2015 07:00 1 G ...
This is simplest, but performance-wise sub-optimal solution. It uses correlated sub-query to calculate on each row: ``` SELECT [NAME] , [TIME] , (SELECT MAX(IsTrue+0) FROM TABLE1 it WHERE DATEADD(DD,1,it.TIME) > ot.TIME AND it.TIME <= ot.Time) [ISTRUE] FROM Table1 ot ``` I don't how much data you have. It wi...
Try this ``` with cte as ( Select Row_Number() over(Partition by convert(date,Time) order by Time)as Rno,Name,Istrue,time from test ) select Rno,Name,Time,Case when Rno>1 then 1 else 0 end as Istrue from cte ``` **Please Check Working** [DEMO](http://www.sqlfiddle.com/#!6/7063d/17)
SQL : Return column value based on previous few rows values
[ "", "sql", "sql-server", "relational-database", "" ]
I have a table with code and Date ``` Code Date ---------------------------- A1 21 May 2015 15:47 A2 21 May 2015 10:30 A3 20 May 2015 10:30 A4 21 May 2015 10:30 A1 19 May 2015 15:20 A2 21 May 2015 12:30 A3 19 May 2015 05:30 A4 18...
This seems to give your expected output, including the two "dashed" results for yesterday: ``` declare @t table (Code char(2),[Date] datetime) insert into @t(Code,Date) values ('A1','2015-05-21T15:47:00'), ('A2','2015-05-21T10:30:00'), ('A3','2015-05-20T10:30:00'), ('A4','2015-05-21T10:30:00'), ('A1','2015-05-19T15:20...
``` select case when cast([Date] as date) >= cast(getdate() as date) then 'Today' else 'Yesterday' end as Flag , Code , Date from ( select row_number() over ( partition by Code, cast([Date] as date) order by [Date] desc) rn ...
Todays latest and yesterdays latest record
[ "", "sql", "sql-server", "sql-server-2008", "sql-server-2005", "sql-server-2012", "" ]
When attempting to do an OPENQUERY from Sybase to Microsoft SQL I run into an error: > Duplicate column names are not allowed in result sets obtained through > OPENQUERY and OPENROWSET. The column name "PatientID" is a duplicate. The query I have built joins 2 tables based on similar admissionID and patientID. For I...
You'll have to alias one of the two duplicate columns and explicitly indicate specific columns in the select at least for one of the tables (the one you've used the alias on it's column): ``` SELECT firstTable.PatID as 'pID', firstTable.column2, secondTable.* FROM... ``` Notice, I've still used a wildcard on the sec...
Duplicate and missing column names are allowed in result sets but not in table definitions (although given the error message, it looks like they wouldn't even be allowed in the result set for this situation anyway). Hence you cannot use the `SELECT *` construct if either of these things occur. You need to specify the f...
How to remove/rename a duplicate column in SQL (not duplicate rows)
[ "", "sql", "sql-server", "sybase", "" ]
I need to write a DB function to concatenate 4 values. These values can be empty or null. How can I concatenate only the values that are not empty or null? ## Pseudo Code ``` CASE WHEN #p1 IS NULL THEN '' ELSE #p1 END || CASE WHEN #p2 IS NULL THEN '' ELSE #p2 END || CASE WHEN #p3 IS NULL THEN '' ELSE #p3 ...
You are replacing null with empty strings? In Oracle null and empty string are the same thing. You don't need to make any decision based on null. So, you can just: ``` expr:= p1||p2||p3||p4; ``` For example if ``` p1 = 'a'; p2 is null; p3 = 'b'; p4 is null; ``` expr `p1||p2||p3||p4` would be `'ab'`.
ANSI SQL: ``` coalesce(#p1,'') || coalesce(#p2,'') || coalesce(#p3,'') || coalesce(#p4,'') ```
CASE Using CASE Statements to check for Null or Empty value
[ "", "sql", "oracle", "case", "concatenation", "" ]
I have 2 models User and Rating as follows: ``` class User < ActiveRecord::Base has_many :ratings end class Rating < ActiveRecord::Base belongs_to :user end ``` Each user receives multiple ratings from 1 - 10. I want to return all users with an average rating of > 5. I've got this so far... ``` User.joins(:rati...
Hope this helps someone in the future. This will find the average rating of each user through the ratings table, and return all users with an average rating above 5. ``` User.joins(:ratings).merge(Rating.group(:user_id).having('AVG(rating) > 5')) ``` .having was my missing link. More examples of .having [here](http:/...
If you're looking at all users, why join first? ``` @avg = Ratings.group(:user_id).average("rating") #returns hash which contains arrays @avg.each do |avg| #0 is user_id, 1 is value puts avg[0] if avg[1] > 5 end ```
rails return list of users with average rating above 5
[ "", "sql", "ruby-on-rails", "ruby", "activerecord", "" ]
I'm new to SAS and have a simple dataset called ORIG\_DATA from which I need to create a new dataset SUMMARY which shows the total by Salesman\_ID by Day\_ID In essence the SUMMARY output should look like this where the numbers are the sum of totals. ``` Salesman_ID|Day_1|Day_2 A |30 |40 B |60 |...
Similar one: ``` proc sort data = orig_data(drop = Other_field); by salesman_id day_id; run; data test (drop = total); retain salesman_id day_id; set orig_data ; by salesman_id day_id notsorted; if first.day_id then sum = total; else sum + total; if last.day_id then output; run; proc transpose data ...
You can solve the problem with a simple data step, see the code below. You need to sort the data first, and then instruct the data to work with groups where you reset the day\_1 and day\_2 to zero at the start of a new group and you output to the data set at the last observation. Let me know if you have any questions....
sas conditional sum into new field
[ "", "sql", "sas", "conditional-statements", "" ]
I have 2 tables ``` 1. emp_mst empcode empname 001 abc 002 def 2. leavetotal empcode leave 001 10 001 5 001 2 002 12 002 8 ``` Now i am trying to get the empcode and empname from the emp\_mst and the total for leave days from leavetotal.I have no idea how to get it. thanks in advance.
`JOIN` / `GROUP BY` solution: ``` select e.empcode, e.empname, SUM(l.leave) from emp_mst e left join leavetotal l on e.empcode = l.empcode group by e.empcode, e.empname ``` `LEFT JOIN` to list even those without any leave. (Do just `JOIN` if not needed.) Correlated sub-select solution: ``` select e.empcode, e.emp...
In the FROM clause you can specify multiple tables, this will result in a cartesian product of the two tables. So each row in the a table will be joined with every other row in all other tables. This is of course not what you want, you only want rows with the same empcode to be joined. So that needs to be specified in ...
How to get the values from 2 tables together in SQL
[ "", "sql", "union", "" ]
Say there's a table ``` Name Salary Joe 4000 Steve 6000 ``` I could just do this ``` select name from emp where salary = (select max(salary) from emp); ``` but is there a way to do this without using a subquery?? Please help. EDIT: Sorry I forgot to mention that I'm using Oracle 10g and LIMIT doesn't work on it
You didn't mention the version of Oracle. On Oracle 12 there is a new low limiting clause that can be used: ``` SELECT name FROM emp ORDER BY salary desc FETCH FIRST 1 ROWS ONLY; ``` There are examples in documentation: <https://docs.oracle.com/database/121/SQLRF/statements_10002.htm#BABEAACC> On ear...
In **`Oracle 12c`**, the **[top-n row limiting](http://docs.oracle.com/database/121/SQLRF/statements_10002.htm#SQLRF55645)** feature is introduced. Which allows to ORDER the rows without an additional subquery. So, no more dependency on ROWNUM and explicit sorting in a subquery. For example, ``` SQL> SELECT ename, sa...
Display the name of the maximum salary holder (WITHOUT USING A SUBQUERY)
[ "", "sql", "oracle", "" ]
I am trying to get the number with the decimal values. Here is the following example: I have two numbers: `621` which should be divided by `7` and result should be shown in the form of number with at least 3 digits decimal values. Accordingly the result should be `88.714`. My Try1: ``` SELECT CAST(621/7 as DECIMAL(...
You have to convert before you divide in order to avoid integer division. Easiest way is: ``` cast(621*1.0/7 as Decimal(5,3)) ``` In your examples, the division is happening first, then the convert/cast is being applied to that result.
Try this ``` SELECT CONVERT(DECIMAL(18,0), 621)/7; ```
Get number with decimal value
[ "", "sql", "sql-server", "" ]
I am using sql-server. I have a table which contains the value of a list of companies. I wish to workout the % of each company as part of this list. See example below ``` name value wgt% abc 10 plm 15 xyz 25 ``` So above is what I have, below is what I would like, ``` name value wgt% abc 10 ...
Use a sub-select to get the total sum: ``` update D_COMP_VALUES set wgt = 100 * value / (select sum(value) from D_COMP_VALUES) ``` But it's normally a bad idea to store computed values. Create a view instead, that never will have inconsistent data!
I would approach this using window functions: ``` with toupdate as select cv.*, sum(value) over () as sumvalue from d_comp_values ) update toupdate set wgt = value / sumvalue; ``` Note that SQL Server does integer division, so if `value` is an integer (as suggested by your sample data), you will ...
update and using sum to calculate column value
[ "", "sql", "sql-server", "sql-update", "" ]
I have a very simple query that returns the Notes field. Since there can be multiple notes, I only want the top 2. No problem. However, I'm going to be using the sql within another query. I really don't want 2 lines in my results. I would like to combine the results into 1 field value so I only have 1 result line in th...
Get the next row's value and filter all but the first row: ``` select ..., rcai.field_value || ' AND ' min(rcai.field_value) -- next row's value (same as LEAD in Standard SQL) over (partition by ra.rnt_agr_nbr order by rcai.field_value rows between 1 following and 1 following) as next_field_v...
``` select *,(SELECT top 2 rcai.field_value + ' AND ' AS [text()] FROM RNT_CUST_ADDNL_INFO rcai WHERE rcai.rea_rnt_agr_nbr = rain.rea_rnt_agr_nbr AND rcai.bac_acct_id=rain.bac_acc_id ...
SQL Combing the top 2 field values into 1 value
[ "", "sql", "teradata", "" ]
i'm a new to sql & forum - need help on how to insert duplicate rows in temp table. Would like to create a view as result ``` View - Employee: Name Empid Status Manager Dept StartDate EndDate AAA 111 Active A111 Cashier 2015-01-01 2015-05-01 AAA 111 Active A222 Sales 2015-05-01 NULL `...
modified query - this yields result of previous & most recent records select e.\*, c.date, c.FW, c.FM, c.FY from employee e join calendar c on e.startdate <= c.date and ISNULL(e.enddate,GETDATE()) > c.date
What you are looking for is a `join` operation. However, the condition for the `join` is not equality, because you want all rows that match between two values. The basic idea is: ``` select e.*, c.date from employee e join calendar c on e.startdate >= c.date and (e.enddate is null or c.date <= e.end...
insert duplicate rows in temp table
[ "", "sql", "" ]
I have good experience in SQL Server, But suddenly I discovered this strange `SELECT` command ``` SELECT $ ``` or ``` SELECT $ FROM tableName ``` All the time it returns zero scalar value (`0.00`), or a new column with all values of `0.00` What is that?
When SQL Server comes across your `$` sign, it automatically converts it into a `money` data type. Because you don't have an explicit value after the dollar sign, SQL Server is assuming `0.00`. From [MSDN](https://technet.microsoft.com/en-us/library/aa172602%28v=sql.80%29.aspx): > When converting to `money` or `smallm...
After a little messing around, I've figured since this happens no matter what currency symbol is used, SQL server is implying that the field is a currency field. If you add numbers after the currency symbol, in this case a dollar so: ``` SELECT $4 ``` SQL server will return 4.00 So SQL Server is taking the use of $...
SELECT $ (dollar sign)
[ "", "sql", "sql-server", "select", "" ]
I have a table like this ``` ID | A | B | InTime | OutTime 10 | 19 | 18078 | 2011-09-07 16:51:56.807 | 2011-11-09 22:39:02.487 ``` But I want to get data in below format ``` ID | A | B | Time 10 | 19| 18078 | 2011-09-07 16:51:56.807 10 | 19| 18078 | 2011-11-09 22:39:02.487 ``` Sorry in adv...
I'd probably go with something simple, like a `union all`: ``` select ID, A, B, InTime [Time] from myTable union all select ID, A, B, OutTime [Time] from myTable ```
Try this: ``` Select ID, A, B, InTime From Table Union All Select ID, A, B, OutTime From Table ```
SQL Server - break single row into two
[ "", "sql", "sql-server", "" ]
Inside of stored procedure you have the code ``` create table #datatable (id int, name varchar(100), email varchar(10), phone varchar(10), cellphone varchar(10), none varchar(10) ...
Just drop the table after select .becoz **it no use to drop table without showing output from temp table used inside the SP** ``` create table #datatable (id int, name varchar(100), email varchar(10), phone varchar(10), cel...
EDIT: You say you have a reason for doing it so ignore my answer below. Answering whether you can drop the temp table then yes you can, and your data **will** still be returned by your stored procedure. You can just put the ``` DROP TABLE #datatable ``` line in after your ``` select * from #datatable ``` line and y...
Present Data in Presentation Layer after Removing the Temp Table
[ "", "sql", "sql-server", "temp-tables", "" ]
I am currently quite stuck with my project on this SQL query that I can't get to work. Here are my tables: ``` [INVENTORY] ==================================================== | ITEM _ID | ITEM_DESC | STOCK | PPU | ==================================================== | 1 | CHAIR WHITE | 2...
Here is what I would do: 1. Separate the two queries. 2. Put your Selection logic into the inline query and sum the results. 3. Left join the two so that you can still see products that don't have any matching reservations. You can do this in one bit query but I think you will find this works better for readability a...
You need to join the three tables together in order for the query to function ``` SELECT INV.ITEM_ID, INV.ITEM_DESC, INV.PPU, INV.STOCK, SUM(I_RSV.QTY) FROM INVENTORY INV JOIN I_RSV ON I_RSV.ITEM_ID = INVENTORY.ITEM_ID JOIN TRANSACTIONS TRN ON I_RSV.TRAN_CODE = TRN.TRAN_CODE WHERE TRN.TRAN_CODE.DATE_OUT < GET...
Stuck with a somewhat complex SQL query
[ "", "sql", "sql-server", "" ]
I have a table with several columns. I need to compare a few of those columns to each other and delete the rows where they match each other or are NULL. To put it differently, I need to leave the rows only where there are differences other than NULL. (If it matters, I'll run this several times against tables with a dif...
``` select * from table where v1 <> v2 or v1 <> v3 or v2 <> v3 ``` This will return rows where there will be `TRUE` for any of pair. So surrounding that predicate with `NOT IN` will give desired set to delete: ``` delete t where id not in(select id from t where v1 <> v2 or v1 <> v3 or v2 <> v3) ``` Here is the fiddl...
``` Delete from tablename where (Value_1 is Null And value_2 is null) or (Value_2 is Null And value_3 is null) or (Value_1 is Null And value_3 is null) or (Value_1 = value_2) or (Value_1 = value_3) or (Value_3 = value_2) ``` This should be able ...
Query to Delete Rows where Columns Match or are NULL
[ "", "sql", "sql-server", "" ]
Why does the MySQL query below give error > # 1066 - Not unique table/alias: 'MOZ' ``` SELECT * FROM GA, MOZ, SF LEFT OUTER JOIN MOZ ON GA.Page = MOZ.URL LEFT OUTER JOIN SF ON GA.Page = SF.Address ```
Simple rule: Don't use commas in the `from` clause: ``` SELECT * FROM GA LEFT OUTER JOIN MOZ ON GA.Page = MOZ.URL LEFT OUTER JOIN SF ON GA.Page = SF.Address; ``` Your version was expressing a full cartesian product between the three tables and *then* trying to do the `left join`s. The specific pro...
The error is pretty clear, you have referenced the table `MOZ` twice, choose another alias for the second table: ``` SELECT * FROM GA, MOZ, SF LEFT OUTER JOIN MOZ AS moz2 ON GA.Page = MOZ2.URL LEFT OUTER JOIN SF ON GA.Page = SF.Address ``` Note that referencing the three table `GA, MOZ, SF` in the `FROM` cla...
LEFT OUTER JOIN on 3 tables. Why does this SQL code give error 106
[ "", "sql", "outer-join", "" ]
I have a column in my table which contains DATEs and I need to keep only the YEAR (=> in a NUMBER or INT type) My idea was to add a column and try something like this : ``` UPDATE myTable SET newColumn=( select to_number(to_char(oldColumn.year, 'yyyy')) from myTable) ``` But I get this error : > single-row subquery...
You need to change your query to: ``` UPDATE myTable SET newColumn=to_number(to_char(oldColumn.year, 'yyyy')) ``` This `SELECT` statement will return all of the rows in the table, from column `oldColumn.year`, which generates your "single-row subquery returns **more than one row**" error. `(select to_number(to_char...
You can use the [`EXTRACT`](http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions050.htm) function: ``` UPDATE myTable SET newColumn = EXTRACT( YEAR FROM oldColumn.year ) ```
How to extract the year of a DATE and insert it in a new column?
[ "", "sql", "oracle", "" ]
I have a table with the following columns: `DATE, TICKER, and ID.` Essentially, what I am trying to do with the code below is select all of the ticker and its corresponding ID's (it can have multiple ID's). However, in the table, there are multiple entries where tickers can have the same ID, but fall under a different ...
`WHERE` clause comes before `GROUP BY` clause does ``` SELECT MIN(DATE), TICKER, ID FROM Names WHERE TICKER IN ('A', 'B') GROUP BY TICKER, ID ```
You are using `GROUP BY` clause before `WHERE` clause, maintain the clause sequences. ``` SELECT MIN(DATE), TICKER, ID FROM Names WHERE TICKER IN ('A', 'B') GROUP BY TICKER, ID ```
Error in mySQL command using 'GROUP BY' and 'WHERE ... IN' together
[ "", "mysql", "sql", "" ]
I am trying to set a query value to NULL in a stored procedure: The query should be: ``` UPDATE [dbo].[tablesym] SET PAYMSTTS=0,SWP=0,IDRM=NULL ``` so, in the stored procedure, I have: ``` SELECT @query21= 'UPDATE [dbo].[tablesym] SET PAYMSTTS=0,SWP=0,IDRM='+NULL ``` However, the column does not update. Neither an...
``` SELECT @query21= 'UPDATE [dbo].[tablesym] SET PAYMSTTS=0,SWP=0,IDRM='+NULL select @query21 -- will result in NULL ``` As simple as that you add anything to infinity result will always be infinity. This is what you need ``` SELECT @query21= 'UPDATE [dbo].[tablesym] SET PAYMSTTS=0,SWP=0,IDRM= NULL' ``` If you ar...
Change the line in your stored proc to this: ``` SELECT @query21= 'UPDATE [dbo].[tablesym] SET PAYMSTTS=0,SWP=0,IDRM=NULL' ```
Set Query Value To NULL in store procedure
[ "", "sql", "sql-server", "sql-server-2008", "" ]
Here is the details:- Table: `tableA` Columns: ``` columnA, columnB ``` Query: ``` Select * from tableA where columnA = columnB ``` I would like to create index for this where clause "columnA=columnB" in Oracle database, is it possible to do that?
Hope it help you ^^ **Creating a Function-Based Index** Function-based indexes facilitate queries that qualify a value returned by a function or expression. The value of the function or expression is precomputed and stored in the index. In addition to the prerequisites for creating a conventional index, if the index...
Query to create index in Oracle: ``` CREATE INDEX idx ON test(id) TABLESPACE idxs_indx; ``` Where * `idx` is the name of the index * `test` is the table name * `id` is the column name * `idxs_indx` is the tablespace name If you want to store all the indexes in a separate tablespace, then tablespace name is require...
How to create index?
[ "", "sql", "oracle", "indexing", "" ]
I'm using SSIS to import data from an Excel spreadsheet into a SQL database. I have this working. I used a data flow task to Import from Excel then Move to OLE DB destination. However, I'd like to use a SQL query to add a column with the current date (i.e. date imported to database) before moving it. The only place I ...
I think I have a solution. I left the SSIS solution unchanged and instead used a trigger in the SQL Server to insert the current date when the table in question is changed.
Instead of using a separate SQL Task, you could use a Derived Column to add the date column inside your existing Data Flow. If you go this route, you'll end up with something similar to <https://stackoverflow.com/a/9512395/117424>.
Execute SQL task while importing Excel file to SQL server
[ "", "sql", "excel", "ssis", "" ]
Have a simple UNION ALL query marrying the results of two queries. The first query, run independently, returns 1208 records and the second 14. I would expect a properly syntaxed UNION ALL to return 1222 records but mine falls to 896. Makes zero sense to me: ``` SELECT a.WBS_ELEMENT_ID as [WBS Element], a.WBS_ELEMENT_...
Your queries should return all rows in the table. Unless the table changes between executions, the results from running the subqueries separately should be the same as from running them with the `UNION ALL`. As a note, if you want to simplify the query, then you can do: ``` SELECT COALESCE(a.WBS_ELEMENT_ID, ...
Here is a simplified example can you see if it works on your server? ``` SELECT a.low AS [My ID], a.name AS [My Letter] FROM master..spt_values as a WHERE low is not null UNION ALL SELECT ROW_NUMBER() OVER (ORDER BY a.name) AS [My ID], a.name AS [My Letter] FROM master..spt_values as a WHERE a.low is null `...
T-SQL [UNION ALL] removing records from query result
[ "", "sql", "sql-server", "t-sql", "union", "union-all", "" ]
i have a MySQL DB in which i have created a table with a **longtext** column in which i store xml files as a string so i am asking if it is possible to get nodes using their names and a specific attribute value! here is an example of xml i deal with : ``` <?xml version="1.0" encoding="ISO-8859-1" standalone="yes" ?> <...
i used this method to get the node as a string and it is working fine : ``` public static String NodeToString(String file,String moid) throws SAXException, IOException, ParserConfigurationException{ String stringNode=""; InputStream in = new ByteArrayInputStream(file.getBytes("ISO-8859-1")); Document d...
MySQL has a very limited functionality when it comes to querying XML data. There is [`ExtractValue()`](https://dev.mysql.com/doc/refman/5.1/en/xml-functions.html#function_extractvalue) function which can be used to get node/attribute value from XML document, but it can't return subtree. Your best bet might be using xp...
how to select a particular node from xml file using node's name and a specific attribute value?
[ "", "mysql", "sql", "xml", "" ]
``` select TO_CHAR(sysdate, 'YEAR')-365 FROM DUAL; ``` I get error > 'invalide number'
Your code ``` select TO_CHAR(sysdate, 'YEAR')-365 FROM DUAL; ``` doesn't work because you try to make an mathematical operation on string value `TO_CHAR(sysdate, 'YEAR')` which is not properly. This will work ``` select EXTRACT(YEAR from sysdate)-365 FROM DUAL; ``` result ``` 1650 ``` but it doesn't make sense, s...
See the result of TO\_CHAR(sysdate-365, 'YEAR') and then think if you can cast this to a numeric value to be able to subtract 365. ``` 'twenty fourteen' - 365 ``` You probably want the previous year's date: ``` add_months(sysdate, -12) ``` Or if you need the year exactly 365 days before today: ``` extract(year fro...
How to_date function with sysdate
[ "", "sql", "oracle", "oracle10g", "" ]
I'd like to retrieve the bill when `charge1 + charge2 is not equal to the BillAmount`, but in the meantime, exclude when `charge1 + charge2 + 0.01 = BillAmount` or when `charge1 + charge2 - 0.01 = BillAmount`. How do I achieve this in sql? The way I did does not work correctly. ``` SELECT BIllAmount, Charge1, Charge2 ...
One of those conditions will be true, because something is not going to be equal. I think the logic you want is: ``` WHERE NOT (BillAmount = Charge1 + Charge2 OR BillAmount = Charge1 + Charge2 + 0.01 OR BillAmount = Charge1 + Charge2 - 0.01 ) ``` This is equivalent to: ``` WHERE Bill...
First you filtered out the row where `billamount <> charge1 + charge2`..Then from that you can apply your next `<>` condition Try below code ``` Select BillAmount, Charge1, Charge2 from ( SELECT BillAmount, Charge1, Charge2 FROM Table WHERE BillAmount <> Charge1 + Charge2 ) as t Where BillAmount <> Charge1 + Charge2 ...
How to exclude data in the where condition while conflicts with another condition
[ "", "sql", "sql-server-2008", "" ]
I have two tables bound through an ID field: > table1: id, name, type > > table2: id, id\_table1, date, status I have to collect all the records of the `table1` that have a certain value of `type` field and that are not been referenced in `table2` plus all the records of `table1` referenced in `table2` that have a ce...
``` SELECT t1.*, t2.* FROM table1 t1 LEFT JOIN table2 t2 ON table2.id_table1 = table1.id WHERE (t1.type= 'value1' AND t2.id IS NULL) OR (t2.status = 'certain status' ) ```
You can try this... ``` SELECT T1.*,T2.* FROM Table1 T1 LEFT JOIN Table2 T2 ON T1.Id=T2.Id_Table1 WHERE T1.Value = 'value1' AND T2.id_table1 IS NULL UNION SELECT T1.*,T2.* FROM Table1 T1 INNER JOIN Table2 T2 ON T1.Id=T2.Id_Table1 WHERE T2.Status= 'Status Criteria' ```
SQL query to find unreferenced records
[ "", "mysql", "sql", "" ]
I have a SQL table with a column named "FileLink" and I need to add the domain name at the end of the server name for all the existing records in the table. So it would be like this: Before: \\ServerName\SharedFolder\Test.PDF After: \\ServerName.domain.net\SharedFolder\Test.PDF So I need to add ".domain.net" to the ...
If you need to modify only one domain and this value is unique you can use REPLACE: ``` update Table set Column = REPLACE(Column, 'ServerName', 'ServerName.domain.net') ```
If you don't want to use the replace statement you can do it like this: ``` Declare @SrvName as varchar(50) Set @SrvName = '\\ServerName' Select '\\ServerName.domain.net'+Substring(FileLink,Len(@SrvName)+1,Len(FileLink)-Len(@SrvName)) ```
Add additional text to an existing string in SQL?
[ "", "sql", "sql-server", "hyperlink", "" ]
``` INSERT INTO #Temp (id, id2, a, b) SELECT id, id2, a, b FROM SomeOneTable ``` We usually get the data from one table, How do we insert the data on temp table if (`id` and `a`) fields are from a separate table and (`id2` and `b`) are from another table. I want all the 4 fields to be in one Temp table.
With `INNER JOIN` for example ``` INSERT INTO #Temp (id, id2, a, b) SELECT TABLE_A.ID, TABLE_B.ID2, TABLE_A.A, TABLE_B.B FROM TABLE_A INNER JOIN TABLE_B ON TABLE_A.[primary_key] = TABLE_B.[foreign_key] ```
Try this one: ``` INSERT INTO #Temp (id, id2, a, b) SELECT id, id2, a, b FROM SomeOneTable a inner join someonetable2 b on a.id=b.id2 ```
How to insert data to a temp table from multiple tables in SQL
[ "", "sql", "sql-server", "" ]
I'm trying to add in the `total price` for a pizza order based on the order `sub-total` and `tax`. I've been getting an error stating the subquery returned more than 1 value with this command: ``` DECLARE @orderTotal AS INT SET @orderTotal = (SELECT(SUM((orderSubtotal+tax) * (1 - discountAmount))) F...
First, this is the wrong way to do it, unless you want all the orders to have the same value in `orderTotalAmount` column. I think you are probably looking for something like this: ``` UPDATE OrderProcessing SET orderTotalAmount = (orderSubtotal + tax) * (1 - discountAmount) ``` Second, I think you have too many br...
I think you don't need a group by but instead it should be something like ``` UPDATE OrderProcessing o SET orderTotalAmount = (SELECT(SUM((orderSubtotal + tax) * (1 - discountAmount))) FROM OrderProcessing WHERE orderID = o.orderId) ``` Otherwise, as the error states, the subquery returns more than one re...
SQL: How to update all rows with a calculation?
[ "", "sql", "sql-server", "t-sql", "sql-update", "" ]
One of a table columns is of VARBINARY type, need to raise a query to evaluate rows for particular bytes pattern, following approach dramatically decreases performance: ``` declare @pattern varbinary // 19 bytes constant set @pattern = 0x00..... -- r.payload is of VARBINARY type as well SELECT .... FROM ... WHERE su...
Here you go, use a [calculated column](https://msdn.microsoft.com/en-ie/library/ms186241.aspx) to store the first 19 bytes, `PERSISTED` so you can index it. [A demonstration can be found here on SQLFiddle.](http://sqlfiddle.com/#!3/b0cb6b/1) When I perform the linked test, the persisted and indexed approach is about ...
Is it possible to create an additional binary column that contains these first 19 bytes? If so, you could either create it as a persisted computed column, or as a 'real' column, and create an `INSERT` trigger that populates it when a record is added (and an `UPDATE` trigger too if the records are updated). You could ...
Performance of varbinary comparison in T-SQL
[ "", "sql", "performance", "sql-server-2008", "t-sql", "comparison", "" ]
Database - Oracle Database 10g Release 10.2.0.4.0 , working with Oracle SQL Developer **EDIT** Sorry: Query-1 Should be : `SELECT TABLE_NAME FROM USER_TABLES;` earlier it was `SELECT OWNER, TABLE_NAME FROM ALL_TABLES;` Output-1: ALL TABLES that I own **Query-2:** `SELECT COUNT(*) FROM MYTABLE_1;` Output-2: Total ...
You want to use the contents of the data dictionary to drive a query. This can only be done with dynamic SQL, in a procedure. Some points to bear in mind: 1. Oracle maintains the SCN Timestamp mapping to support Flashback Query. It just keeps the mapping for the supported UNDO\_RETENTION period. So we can use SCN\_TO...
I don't have enough rep to post a comment however the reason why StevieG's answer is still returning an error is because you don't have access to the dba\_tab\_modifications view, instead use user\_ / all\_ equivalents in-line with your permissions: ``` SELECT a.OWNER, a.TABLE_NAME, a.NUM_ROWS, b.TIMESTAMP FROM ALL_TA...
Combine results of multiple queries in Oracle Sql
[ "", "sql", "oracle", "" ]
I am trying to write an SQL statement producing the below output. I have the two following tables: **UserMovie** ``` userID | movieID ----------------- 135 | k0jps 135 | p1zka 125 | v0t67 115 | opp2s 111 | xnwri 115 | kspdl ``` **Follows** ``` followerid | followingid ---------------------...
Try this to include users with no follows: ``` SELECT UserId, Count(followerid) AS followerCount FROM (SELECT DISTINCT userId FROM UserMovie ) m LEFT JOIN Follows f ON f.followingid = m.userID GROUP BY UserId ``` Now it generates : ``` UserId followerCount 111 2 115 0 125 1 135 1 ```
Here's one approach: get a distinct list of `userID` from `UserMovie` in an inline view (use either a `GROUP BY` or a `DISTINCT` keyword), and perform an "outer join" operation of that to the `Followers` table to find followers. Collapse the rows from that with a `GROUP BY`, and use an aggregate function to get a count...
SQL query that produces the following output?
[ "", "mysql", "sql", "relational-database", "" ]
In Oracle Sql developer 11g, how do I generate a random integer and assign it to a variable? This is what I've tried so far: ``` S_TB := SELECT dbms_random.value(1,10) num FROM dual; ``` With this code I got error: ``` S_TB := SELECT dbms_random.value(1,10) num FROM dual Error report - Unknown Command ``` What is t...
Variables require PL/SQL; it's not clear from your question whether your code is a proper PL/SQL block. In PL/SQL variables are populated from queries using the INTO syntax rather than the assignment syntax you're using. ``` declare txt varchar2(128); n pls_integer; begin -- this is how to assign a litera...
For a set of consecutive integers randomly distributed uniformly (in the example below between 1 and 10), I suggest: ``` select round(dbms_random.value(0.5,10.49999999999),0) from dual ``` Otherwise I'll unintentionally restrict the first and last number in the set to half the probability of being chosen as the rest ...
PLSQL generate random integer
[ "", "sql", "oracle", "plsql", "oracle11g", "oracle-sqldeveloper", "" ]
**SOLVED** I'm stuck with something and I'm not even sure if it's possible what I'm trying to do. Basically I want to update (or better yet, right away with the insert) a specific field with a multiplication from the current table AND a value from another table. This is the query so far : ``` UPDATE Orders SET Tot...
I think you want the subquery correlated with the outer query: ``` UPDATE Orders SET Total = (SELECT p.Price * orders.Quantity FROM Products as p WHERE p.ProductID = 110 ) WHERE orders.OrderID = 112; ``` Your version takes `quantity` from the orders for produc...
You can directly join with the said table and perform the updation accordingly like ``` UPDATE Orders INNER JOIN Products ON Products.ProductID = Orders.ProductID AND Products.ProductID = 110 AND Orders.OrderID = 112 SET Total = Products.Price * Orders.Quantity; ```
UPDATE / INSERT calculated values from 2 tables
[ "", "sql", "ms-access", "" ]
I have a dataset: ``` variable value zip interval score a 10 10017 10 8 a 10 10017 10 10 a 10 10017 11 12 a 10 10017 11 8 a 10 10018 10 8 a 10 10018 10 10 a 10 10018 11 12 a 10 10018 11 ...
Try this: ``` select variable,value,zip,interval, max(score) from tab group by variable,value,zip,interval ```
Try this ``` select variable,value,zip,interval,max(score) from tab group by variable,value,zip,interval ```
Select max of a column with multiple condition
[ "", "sql", "oracle", "" ]
I am trying to do a simple reservation system, and I would like to have an sql query to check if the dates are available and that no date in the date range is taken. Example: there is this date taken: 2016-01-01 -> 2016-01-08 And I have to check dates like: * 2015-12-25 - 2016-01-03 * 2015-12-25 - 2016-01-20 * 2016-0...
``` For future reference for anyone who has this problem, here is how I solved my issue : $query = "SELECT * FROM booking WHERE "; $query .= "checkInDate >= $chkInDate AND checkOutDate >= $chkOutDate OR "; $query .= "checkInDate >= $chkInDate AND checkOutDate <= $chkOutDate OR "; $query .= "ch...
Two periods (s1,e1) and (s2,e2) **overlap** when s1 <= e2 and e1 >= s2: ``` SELECT * FROM tab WHERE checkInDate <= DATE '2016-01-03' AND checkOutDate >= DATE '2015-12-25'; ``` A period (s2,e2) is **contained** in period (s1,e1) when s1 <= s2 and e1 >= e2: ``` SELECT * FROM tab WHERE checkInDate <= DATE '2015-12-25' ...
check if dates fall in range dates
[ "", "mysql", "sql", "" ]
I'm new to SQL and trying to get a handle on joins and referencing. Databases look like this: **Players** ``` id | name ----+------- 1 | john 2 | tim 3 | frank 4 | tony 5 | mark ``` **Matches** ``` id | winner | loser ----+--------+------- 1 | 2 | 4 2 | 3 | 4 3 | 4 | 5 ...
You are almost there: ``` select matches.id, w.name as winner, l.name as loser from matches join players w on matches.winner = w.id join players l on matches.loser = l.id; ```
You need to alias the table names so you can specify which join the data should come from. ``` select matches.id, p1.name as winner, p2.name as loser from matches join players p1 on matches.winner = p1.id join players p2 on matches.loser = p2.id; ```
SQL: How can I select two IDs as two names from the same table?
[ "", "sql", "postgresql", "" ]
I have a table that looks like this. ``` ID Name Country Published 1 Madrid 0 2 Madrid Spain 1 3 Paris France 0 4 London England 0 ``` In any case where the name is the same, I need to copy the Country from the Published=1 entry to the Published=0 entry. I've been doing it by han...
Do it with join: ``` DECLARE @t TABLE ( ID INT , Name VARCHAR(20) , Country VARCHAR(20) , Published BIT ) INSERT INTO @t VALUES ( 1, 'Madrid', NULL, 0 ), ( 2, 'Madrid', 'Spain', 1 ), ( 3, 'Paris', 'France', 0 ), ( 4, 'London', 'England', 0 ) UPDATE t1 SET Co...
``` UPDATE mytable SET Country= a.Country from (SELECT Country,id FROM mytable WHERE Published = 1) a WHERE Published=0 and a.name=mytable.name ```
Copy a column to another row that has duplicate value
[ "", "sql", "sql-server", "" ]
i try to get results from table with multiple where and/or clauses. My SQL statement is: ``` SELECT * FROM tbl WHERE m__Id = 46 AND t_Id = 2 AND (Cab = 2 OR Cab = 4) ``` How i can get this with Laravel Eloquent? My Code in Laravel is: ``` $BType = CabRes::where('m_Id', '=', '46') ->where('t...
Using [advanced wheres](http://laravel.com/docs/5.0/queries#advanced-wheres): ``` CabRes::where('m__Id', 46) ->where('t_Id', 2) ->where(function($q) { $q->where('Cab', 2) ->orWhere('Cab', 4); }) ->get(); ``` Or, even better, using `whereIn()`: ``` CabRes::where('m__Id', ...
Also, if you have a variable, ``` CabRes::where('m_Id', 46) ->where('t_Id', 2) ->where(function($q) use ($variable){ $q->where('Cab', 2) ->orWhere('Cab', $variable); }) ->get(); ```
Laravel 5 Eloquent where and or in Clauses
[ "", "sql", "laravel", "eloquent", "" ]
I have two int columns in my table. I want to concatenate them like a string for example : `A = 12345 , B = 2` I want to return `123452`. How can I do that ?
Try like this: ``` select CAST(A as varchar(10)) + CAST(B as varchar(10)) ``` **[SQL DEMO](http://www.sqlfiddle.com/#!6/9eecb7db59d16c80417c72d1/1305)**
You can use something like below ``` SELECT NUMBER_COL1, NUMBER_COL2, CAST(NUMBER_COL1 AS VARCHAR(10)) + CAST(NUMBER_COL1 AS VARCHAR(10)) JOINED_NUM FROM TABLE; ```
Sql concatenate integer columns to string
[ "", "sql", "sql-server", "" ]
There is a column in a table, which should store Checksum for list of columns, but I'd like to create it as a default value for this table: ``` CREATE TABLE tblVitalyTest (id BIGINT IDENTITY(1,1), startTime DATETIME, value1 INT, value2 INT, value3 INT, value4 DATETIME, BinCheckSum BIGINT) GO ALTER TABLE tblVitalyTest ...
Basically you can't. But you can do something similar with a trigger. See below ``` SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TRIGGER dbo.tblVitalyTestUpdateInsertTrigger ON dbo.tblVitalyTest AFTER INSERT, UPDATE AS BEGIN SET NOCOUNT ON; UPDATE vt SET vt.BinCheckSum = BINARY...
You can create the column as a computed column. Try this ``` CREATE TABLE tblVitalyTest (id BIGINT IDENTITY(1,1), startTime DATETIME, value1 INT, value2 INT, value3 INT, value4 DATETIME, cksum AS BINARY_CHECKSUM(value1,value2, value3, value4 )) GO ``` Or you can ALTER and existi...
TSQL BINARY_CHECKSUM as a default value
[ "", "sql", "sql-server", "t-sql", "" ]
1I need to deduplicate a table like this:- ``` name | fix | mobile -----+-----+--------- dan | 1 | 1 jon | 1 | 3 mia | 1 | 4 ken | 5 | 4 ``` I want to get:- ``` dan | 1 | 1 jon | | 3 mia | | 4 ken | 5 | ``` It is possible with Excel, but for 500k rows I get `'not responding'` Access remo...
It is possible in sql. I did write sql code.let's say you have id column in table and your table name is **people**. I wrote code for updating '**fix**' column. The trick is joining the table with itself. If you have any question feel free to ask. ``` update temp1 set temp1.fix='' from people temp1 inner join...
Use this query: ``` SELECT t.NAME, IIF(t.partRankFix = 1, t.fix, NULL) AS fix, IIF(t.partRankMobile = 1, t.mobile, NULL) AS mobile ,A.field1, A.field2 FROM ( SELECT A.Name, A.Fix, A.mobile , Sum(IIF(A.fix = B.fix OR A.fix=B.mobile, 1, 0)) AS partRankFix , Sum(IIF(A.mobile ...
Deduplication by two columns
[ "", "sql", "ms-access", "vba", "" ]
I have this sql script that creates a table in my MySql database. ``` CREATE TABLE USER_ACCOUNT (ID DECIMAL(10) NOT NULL, USERNAME VARCHAR (50) NOT NULL, PASSWORD VARCHAR (25) NOT NULL, EMAIL VARCHAR (50) NOT NULL, FIRST_NAME VARCHAR (25) NULL DEFAULT NULL, MID...
As what Giorgos Betsos mentioned in the comments above, I changed `DECIMAL(10)` to `BIGINT` and it worked fine.
Use for the ID integer datatype. ``` ALTER TABLE `user_account` CHANGE `ID` `ID` BIGINT NOT NULL ; ALTER TABLE `user_account` CHANGE `ID` `ID` BIGINT NOT NULL AUTO_INCREMENT ; ``` --- For auto increment you have to use a **integer data type**: TINYINT, SMALLINT, MEDIUMINT, INT, BIGINT A typical data type for a ind...
MODIFY COLUMN error in MySQL
[ "", "mysql", "sql", "" ]
I am trying to execute a query but its not working out so well for me. I got these tables: ``` create table spelare( Spnr char(13), Snamn varchar (20), primary key (Spnr) )engine=innodb; create table speltillfalle( starttid varchar (15), Tnamn varchar (20), Spnr char (13), resultat char (10), ...
Based on your description you simply add this as a WHERE-condition: ``` SELECT Spnr FROM spelare UNION SELECT Spnr FROM speltillfalle WHERE resultat = 'Diskad'; ``` Or you use a EXISTS: ``` SELECT Spnr FROM spelare AS s WHERE EXISTS ( SELECT * FROM speltillfalle AS sf WHERE s.Spnr = sf.Spnr AND result...
Use [`Exists`](https://dev.mysql.com/doc/refman/5.0/en/exists-and-not-exists-subqueries.html) like this: ``` SELECT Spnr, Snamn FROM spelare WHERE EXISTS ( SELECT 1 FROM speltillfalle WHERE resultat = 'Diskad' AND Spnr = spelare.Spnr ); ```
SQL Query help using UNION or nested queries
[ "", "mysql", "sql", "union", "" ]
I have a few question about Dates in Oracle. Is it possible to get the interval (in days) between two DATE types? If yes, is it possible to do a statement (an insert into for example) for each day in this interval? I thought about ``` while (a_sequence != difference_between_dates) LOOP a_sequence.next -- do thing...
Sure. If you're looking for a PL/SQL solution (you can do it in pure SQL but it's probably a bit harder to read), something like ``` DECLARE l_first_date date := date '2015-01-01'; l_last_date date := date '2015-12-31'; l_date_to_check date; BEGIN FOR i IN 1 .. l_last_date - l_first_date LOOP l_date_to_...
May this code help you ``` DECLARE first_date DATE := TO_DATE ('01012015', 'DDMMYYYY'); last_date DATE := TO_DATE ('31012015', 'DDMMYYYY'); a_sequence NUMBER := 25; BEGIN LOOP IF a_sequence = last_date - first_date THEN EXIT; END IF; DBMS_OUTPUT.put_line ('Seque...
Interval between two Dates
[ "", "sql", "database", "oracle", "date", "" ]
I do have a table license\_Usage where which works like a log of the usage of licenses in a day ``` ID User license date 1 1 A 22/2/2015 2 1 A 23/2/2015 3 1 B 22/2/2015 4 2 A 22/2/2015 ``` Where I want to Count how many licenses p...
You can use something like this: ``` select top 1 * From ( select count(license) as Quantity,[user],[date] From license_Usage Group by [date], [user] ) as result order by Quantity desc ``` If you need to have a fetch that fetches all the rows that have max in case there's several, then you'll have ...
Use `RANK` to rank the users by the number of licenses per day. ``` SELECT LicPerDay.*, RANK() OVER (PARTITION BY [date] ORDER BY Qty DESC) AS User_Rank FROM ( SELECT COUNT(license) AS Qty, User, [date] FROM license_usage GROUP BY User, [date] ) LicPerDay ``` Any user with `User_Rank` = 1 will h...
Return max value from a SQL selection
[ "", "sql", "sql-server", "sql-server-2012", "" ]
I have a below query which have a date filter like `EST_PICK_DATE between '2015-02-01' and '2015-06-01'`, where the logic is `EST_PICK_DATE` should be 3 months from the current month and 1st date of next month. I.E for current month MAY, `EST_PICK_DATE` should be between `'2015-02-01'` and `'2015-06-01'`. I need to w...
Try this ``` INSERT INTO STG_Open_Orders (Div_Code, net_price, gross_price) SELECT ord.DIV_CODE AS Div_Code, ord_l.NET_PRICE AS net_price, ord_l.gross_price AS gross_price, FROM ORD ord inner join ORD_L ord_l ONord.ORD_ID=ord_l.ORD_ID WHERE ord_l.EST_PICK_DATE BETWEEN DATEADD(m, DATEDIFF(m, 0,DATEADD(month,-3,getdate...
You can use [`GETDATE()`](https://msdn.microsoft.com/en-us/library/ms188383.aspx) and some sql tricks to get the first day of the month: ``` INSERT INTO STG_Open_Orders (Div_Code, net_price, gross_price) SELECT ord.DIV_CODE AS Div_Code, ord_l.NET_PRICE AS net_price, ord_l.gross_price AS gross_price, F...
Need to write query for Date logic
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have a table that closely resembles the following format: ``` ID | Month_ID | Param1 | Param2 1 | 1 | 5 | 10 1 | 1 | 6 | 12 1 | 2 | 4 | 9 1 | 2 | 8 | 15 2 | 1 | 3 | 17 2 | 1 | 5 | 12 2 | 2 | 3 | 11 2 | 2 ...
This should work with custom month ranges (although assumes the months are all present between min and max for each ID): Dummy data with different month ranges: ``` data input ; do ID=1 to 2 ; do month_id=3+ID to 20-ID*2 ; parm1=int(ranuni(1)*100) ; parm2=int(ranuni(1)*100) ; output ; end ...
I can't think of a way to do it directly in proc univariate but I would probably expand and regroup the data as below: ``` *dummy data ; data input ; do ID=1 to 2 ; do month_id=1 to 12 ; parm1=int(ranuni(1)*100) ; parm2=int(ranuni(1)*100) ; output ; end ; end ; run ; data expand ; set...
Accumulated Monthly Percentile Calculation in SAS PROC SQL
[ "", "sql", "sas", "proc-sql", "" ]
Currently my code is something like this. ``` select * from tblReq where ReqID in (select ReqID from tblLog where LogDate >= '2015/04/01' and LogDate < '2015/05/31') ``` Just wondering how actually the database find the result for this query? Is it re-run every time it ran in sub-query? And is there any script wher...
Yes, you can store the result in a variable and reuse it several times later. In your case, it will be a `table variable` as you could have multiple items. Then, simple `join` it to the initial query: ``` DECLARE @Logs TABLE ( [LogID] INT ); INSERT INTO @Logs ([LogID]) Select tblLog.ReqID from tblLog where tblL...
You can create a [`view`](https://technet.microsoft.com/en-us/library/ms187864(v=sql.105).aspx) if you want to refer to your query later ``` CREATE VIEW V1 AS SELECT tblLog.ReqID FROM tblLog WHERE tblLog.LogDate >= '2015/04/01' AND tblLog.LogDate < '2015/05/31' ``` Per to the comment below, you can use a `table valu...
Set MS Sql result in variable and reuse it
[ "", "sql", "sql-server", "t-sql", "" ]
I have a SQL Server `View`, and It has a field like this `ISNULL(co.[MyValue],0) AS MyValue` in the select. `MyValue` in its table is a *Nullable* field, now I want to return `0` if the value is null but keep the field *Nullable*. I want this because I don't want to change the Entity Framework EDMX file which has thi...
I think you should try **COALESCE** ``` COALESCE(co.[MyValue],0) ```
Use a `CASE` statement ``` SELECT CASE WHEN [MyValue] IS NULL THEN 0 ELSE [MyValue] END FROM yourtable ```
How to return a field as Nullable from a View
[ "", "sql", "sql-server", "" ]
1:Table COUNTRY ``` ID NAME 1 USA 2 BRITAIN ``` 2:Table PEOPLE ``` P_ID P_NAME 4 JOHN 5 MONTY ``` Resultant table should have ``` ID NAME P_ID P_NAME 1 USA 4 JOHN 2 BRITAIN 5 MONTY ``` Just side by side merge. Is it possible? LIK...
Example ``` with x as ( select id, name, rownum rn from country order by id), y as( select p_id, p_name, rownum rn from people order by p_id) select id,name,p_id,p_name from x left join y on y.rn = x.rn union select id,name,p_id,p_name from y left join x on y.rn = x.rn ```
If I well understood your question this could work: ``` SELECT * FROM (SELECT T1.*,ROWNUM AS R FROM COUNTRY T1) V1, (SELECT T2.*,ROWNUM AS R FROM PEOPLE T2) V2 WHERE V1.R = V2.R(+) ``` But you need to know wich table is bigger and I fear you aren't going to to get reliable results
Oracle DB Just Combine Two tables Side By Side
[ "", "sql", "oracle", "" ]
Can you help me write a `SELECT` statement that returns a single row having columns for each TypeId involved for the transaction number 55? ``` CREATE TABLE Types ( Id INT IDENTITY(1,1) NOT NULL, Name VARCHAR(100) NOT NULL, CONSTRAINT PK_Types PRIMARY KEY CLUSTERED(Id) ) GO INSERT INTO Types VALUES ('Type1') ,('Type...
``` SELECT TransactionNumber ,sum(CASE WHEN TypeId = 1 THEN Amount ELSE 0 END) AS Type1 ,sum(CASE WHEN TypeId = 2 THEN Amount ELSE 0 END) AS Type2 ,sum(CASE WHEN TypeId = 3 THEN Amount ELSE 0 END) AS Type3 ,sum(CASE WHEN TypeId = 4 THEN Amount ELSE 0 END) AS Type4 ,sum(CASE WHEN TypeId = 5 THEN Amou...
I think you can do a `PIVOT` to get required output: ``` SELECT * FROM ( SELECT ty.NAME, ISNULL(Amount,0)Amount FROM TRANSACTIONS t INNER JOIN Types ty ON ty.Id = t.TypeId WHERE TransactionNumber = 55 ) sub PIVOT( SUM(Amount) FOR [Name] IN ([Type1], [Type2], [Type3], [Type4], [Type5]) ) ...
Case statement with grouping
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I went through many questions on this site but wasn’t able to find solution. I’ve got a table: ``` Date GroupID CHANNEL 24/02/2015 1 A 26/02/2015 1 B 27/02/2015 1 C 21/03/2015 2 D 20/02/2015 3 E 25/02/2015 3 D 28/02/2015 4 C 04/03/2015 5 B 05/03/2015 5 E 10/03/2015 5 D 11/03/2015 5 ...
One solution could be to use windowed aggregate functions: ``` select *, case when date = MIN(date) over (partition by groupid order by groupid) then 'TRUE' else 'FALSE' end isFirst, case when date = MAX(date) over (partition by groupid order by groupid) then 'TRUE' else 'FALSE' end isLast, count(*) ...
You can use `ROW_NUMBER` to get the `isFirst` and `isLast` column and `COUNT(*) OVER()` for the `ChannelsInGroup`. Additionally, you can use `CROSS APPLY` to compute for the `DaysBeforeLast`: [**SQL Fiddle**](http://sqlfiddle.com/#!6/2cf74/1/0) ``` WITH Cte AS( SELECT *, RN = ROW_NUMBER() OVER(PARTITION B...
Select new columns based on group order
[ "", "sql", "sql-server", "group-by", "sql-order-by", "" ]
I'm new to SQL and I'm currently trying to learn how to make reports in Visual Studio. I need to make a table, graph and few other things. I decided to do matrix as the last part and now I'm stuck. I write my queries in SQL Server. I have two tables: Staff (empID, StaffLevel, Surname) and WorkOfArt (artID, name, curat...
The easiest way to do this is most likely with inner select in the select clause, with something like this: ``` Select S.empID, (select count(*) from WorkOfArt C where C.Curator = S.empID) as CuratorTotal, (select count(*) from WorkOfArt H where H.HelpingCurator = S.empID) as HelpingCuratorTotal FROM...
From a performance perspective, the following query is probably a little more efficient ``` select e.EmpId, CuratorForCount, HelpingCuratorForCount from Staff s inner join ( select Curator, count(*) as CuratorForCount from WorkOfArt group by Curator) mainCurator on s.EmpId = mainCura...
How to join two SQL queries into one?
[ "", "sql", "sql-server", "" ]
I have data inside a column like ``` ## col1 ## ---------- (30)25802112 32(89)02212 (32)2330 ``` need output like ``` ## output ## ---------- 25802112 3202212 2330 ``` is there any simple update something like that can work in my case Thanks in advance for help
Try this: ``` Select case when charindex('(',col1) > 0 and charindex(')',col1) > 0 then substring(col1, 1, charindex('(',col1) -1) + substring(col1, charindex(')', col1) + 1, len(col1)) else col1 end as col1 from TableName ```
1. Find the CharIndex of the character ) . 2. Add 1 to it. 3. Use the Substring function to get that part of the string, starting from result of Step 2 and asking for Len(string). Note : If all column values are unlikely to contain the right brace, then you may have to use a Case Statement to handle those that do and ...
replace numbers inside the brackets
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I've got a table which has the following data: ``` Record Type MID CvvId Date Amount ------------- ---------- ------------- ------------- --------- 2E 8715613516 2014-25-03 27.12 3E asd51...
I got it to work. As recommended above, added a new auto-increment (not necessarily P.k) field as Tid. and wrote the following query: - SELECT p.MID, LEAD(p.CvvId) OVER (ORDER BY p.Tid) NextCvv, LEAD(p.RecordType) OVER (ORDER BY p.Tid) NextRecordType FROM table p after filtering through the record set, on some busine...
I changed your table by adding a transactionId column which is unique for both 2E and 3E records as follows ``` create table tableE( TId int, rtype varchar(20), MID varchar(20), CvvId varchar(20), date date, amount decimal(18,2)) ``` Then following SELECT statement will help you combine them into a single row...
Reading 2 rows together from SQL Server table
[ "", "sql", "sql-server", "" ]
How do i achieve the multiple case condition? The below say invalid syntax ``` SUM(CASE WHEN b.SnapshotDtm = getdate() THEN CASE WHEN (GenderCd = 'F' And EthnicGroupCd = 'N/A') THEN (TechAnnualizedExitsPct_M - TechAnnualizedExitsPct_F) * (TechRepresentCnt_F)/ (365/FiscalYear...
Your nesting is off. You're missing a few `END`s: ``` SUM( CASE WHEN b.SnapshotDtm = getdate() THEN CASE WHEN (GenderCd = 'F' And EthnicGroupCd = 'N/A') THEN (TechAnnualizedExitsPct_M - TechAnnualizedExitsPct_F) * (TechRepresentCnt_F)/ (365/FiscalYearDayNbr) ELSE CASE WHEN (Et...
You're actually missing a few `END`s for each opened `CASE`. Try this: ``` SUM(CASE WHEN b.SnapshotDtm = getdate() THEN CASE WHEN (GenderCd = 'F' And EthnicGroupCd = 'N/A') THEN (TechAnnualizedExitsPct_M - TechAnnualizedExitsPct_F) * (TechRepresentCnt_F)/ (365/FiscalYe...
Multiple case condition
[ "", "sql", "" ]
``` D: cd Tools/MySQL5/bin mysql -u root mysql use xyz; source C:/Users/abc/Desktop/xyz.sql; \q ``` When I run the above lines in command prompt it works fine but when I save it as a batch file and run the file it connects to mysql but doesn't perform the sql scripts.
Now what I see is wrong here is that while executing the above commands one by one in your prompt, once you run `mysql -u root mysql`, you are in the mysql console. So your `source` command would work there but would not work in your batch since you are not in mysql console while running the batch file. Solution: What...
You could write something like this ``` mysql -u dbUsername yourDatabase -e "SELECT * FROM table;" ``` Or to run repeating tasks create a runtasks.bat file, save under the root of your project then write your cmd tasks inside ``` mysql -u dbUser -e "DROP DATABASE IF EXISTS testDatabase;" mysql -u dbUser -e "CREATE D...
Run sql script using batch file from command prompt
[ "", "mysql", "sql", "batch-file", "cmd", "" ]
I'm trying to make a simple query to find the average car sales per month from a table called "salestransaction". My code: ``` select to_char(st.dateofsale, 'MON') as mnth, count(*) / 2 as Average_Car_Sales from salestransaction st group by to_char(st.dateofsale, 'MON') order by to_char(st.dateofsale,...
An easy approach is to add month number to group by, then order by this field: ``` select to_char(st.dateofsale, 'MON') as mnth, count(*) / 2 as Average_Car_Sales from salestransaction st group by EXTRACT(month FROM st.dateofsale), to_char(st.dateofsale, 'MON') order by EXTRACT(month FROM st.dateofsal...
My recommendation: ``` order by min(st.dateofsale); ``` That is, just pull a value out for each group and use that for the ordering. If you have data from multiple years, the above might not work. Instead: ``` order by min(extract(month from st.dateofsale)) ```
order by month oracle
[ "", "sql", "oracle", "" ]
If anyone knows how to use case in query for jtable, pls take a look my code. ``` Dim batch_status As String = " case when status = 0 then 'Created' when status = 1 then 'Scanning' when status = 2 then 'Scan Saved' end as status" cmd.CommandText = "SELECT * FROM ( SELECT ROW_NUMBER() OVER ( ORDER BY " & jtSorting & ...
Just found, change `.status = Convert.ToInt32(item(7))` to `.status = item(7).ToString,` displaying in **Jtable** is quite different
may be the problem with @jtStartIndex AND @jtEndIndex.
vb.net - using case select query in sql for jtable
[ "", "sql", "vb.net", "jquery-jtable", "" ]
``` I have table following this format : Id BillNo: Voucher No: 1 W2015-16/0001 W2015-16/0001 2 W2015-16/0002 W2015-16/0002 3 W2015-16/0003 W2015-16/0003 4 W2015-16/0004 W2015-16/0004 5 W2015-16/0005 W2015-16/0005 6 W2015-16/0006 W2015-16/0006 7 W2015-16/0007 W2015-16/0007 8 ...
``` UPDATE YourTable SET BillNo = SUBSTRING(BillNo,1,1) + SUBSTRING(BillNo,10,4) + '/' + SUBSTRING(BillNo,2,7) , VoucherNo = SUBSTRING(VoucherNo,1,1) + SUBSTRING(VoucherNo,10,4) + '/' + SUBSTRING(VoucherNo,2,7) ``` Test: ``` DECLARE @a NVARCHAR(max) = 'W2015-16/0001' SELECT SUBSTRING(@a,1,1) + SUBSTRING(@a,10,4) + '...
Assuming everything is in a fixed format, then you would just use `update` and string manipulations: ``` update table t set billno = left(billno, 1) + right(billno, 4) + '/' + substring(billno, 2, 7), VoucherNo = left(VoucherNo, 1) + right(VoucherNo, 4) + '/' + substring(VoucherNo, 2, 7); ```
Update multiple columns with Different Values
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I want to get the Name from this table but I only have the Number which is not unique. How do I get the correct Name (please give me some SQL syntax)? Below the database table you can see the input and expected output for ``` Database Table Number Name 1 Anna 1 Anna 2 Brad 2 NULL 2 NULL 2 ...
A simple MAX/GROUP BY will return your expected result set: ``` SELECT Number, MAX(Name) FROM table name GROUP BY 1; ``` Btw, NUMBER is a Reserved Name in Teradata
This is a step in the right direction, the problem is that you will still get NULL aswell if you have a row with NULL give me a bit to figure out how to filter those out if there is a name Mysql would be this: <http://sqlfiddle.com/#!9/4beca/1> ``` SELECT DISTINCT Name FROM mytable WHERE Number=1 AND Name is not null...
Retrieve one row in select statement which generates multiple rows (by avoiding NULL rows if possible)
[ "", "sql", "teradata", "" ]
Is there a "rule set" for when the AS keyword is optional vs required, or is it solely contextual, based on the language specifications for the statements it is used in? For example, when being used for alias it is optional. It's also optional when being used to declare variables (and I believe to use `cast` too). ...
You are in essence asking for the language design decision on when (and why) the AS keyword is optional or required. While this is impossible to answer definitively without referencing the minutes of the design committee meetings, it is likely required **exactly where needed to make an unambiguous grammar**, and option...
I don't have any formal rules for you, but from a practical perspective, for column aliases, I always use AS, as IMO it sometimes makes the intent of the code easier to follow. e.g. : ``` create table dbo.Table1 (id int primary key, col1 varchar(100), col2 varchar(100), Name varchar(100)) insert dbo.Table1 (id, col...
When is the AS keyword optional vs required?
[ "", "sql", "sql-server", "t-sql", "alias", "" ]
Such SQL query: ``` SELECT ROW_NUMBER() OVER (PARTITION BY ID, YEAR order by ID ), ID, YEAR from table t ``` give me following query set: ``` 1 1000415591 2012 1 1000415591 2013 2 1000415591 2013 1 1000415591 2014 2 1000415591 2014 ``` How could I update records with ROW\_NUMBER() equals to 2? Other ...
Try to use [ROWID](http://docs.oracle.com/cd/B19306_01/server.102/b14200/pseudocolumns008.htm) field: ``` UPDATE T SET t.year = t.year*1000 WHERE (rowid,2) in (SELECT rowid, ROW_NUMBER() OVER (PARTITION BY ID, t.YEAR order by ID ) FROM T) `...
You could use a **MERGE** statement which is quite verbose and easy to understand. For example, ``` MERGE INTO t s USING (SELECT ROW_NUMBER() OVER (PARTITION BY ID, YEAR order by ID ) RN, ID, YEAR FROM TABLE t ) u ON (s.id = u.id) WHEN MATCHED THEN UPDATE SET YEAR = some_value WHERE u.RN = 2) / ``` **Note** Y...
How to update rows based only on ROW_NUMBER()?
[ "", "sql", "oracle", "oracle11g", "" ]
I have 2 linked SQL servers, Both are SQL Server 2012 Express Edition. I was executing insert statement into a table of connected SQL Server and it was working perfect until now. I have changed nothing. but now it gives me the following error message. **MSDTC on server 'MSERVER1-PC\SQLEXPRESS' is unavailable.** I hav...
To enable MSDTC on the business management server that is running on Windows Server 2008 click Start, Run, type `dcomcnfg` and then click OK to open Component Services. In the console tree, click to expand Component Services, click to expand Computers, click to expand My Computer, and click to expand Distributed Trans...
In my case the problem was not MSDTC server either. I had to disable "Enable Promotion of Distributed Transaction" option under Linked Server properties -> Server Options.
MSDTC on server 'MSERVER1-PC\SQLEXPRESS' is unavailable
[ "", "sql", "sql-server", "msdtc", "" ]
So I have a reference field in my database with contains data like this: ``` R8, R9, R1, R2, R3, R4, R5, R6, R7 ``` I would like to rearrange this field to look like this: ``` R1, R2, R3, R4, R5, R6, R7, R8, R9 ``` Furthermore, there is also some other types of descriptions, like this: ``` C7 (OP1 to OP12), C10 (...
Here is how you can do this: ``` with cte as(select F1.id,   F1.data,  O.splitdata from  (select *,  cast('<X>'+replace(replace(F.data, '&', '&amp;'),', ','</X><X>')+'</X>' as XML) as xmlfilter from t F)F1  cross app...
This is not a function that I created.. but I think this will help you. This was created by Andreas Goldman. First run this query to create the function called F\_ConvertStringToTable ``` CREATE FUNCTION F_ConvertStringToTable ( @List VARCHAR(MAX), -- Separerad lista av värden @Delimiter CHAR(1) -- Avgränsare/separat...
Rearrange string in SQL
[ "", "sql", "sql-server", "string", "sorting", "" ]
I want to delete first 500 records from my table without any condition. Table definition is as follow: ``` CREATE TABLE txn_log ( txn_log_timestamp timestamp without time zone NOT NULL, txn_log_pgm_id character(6) ) WITH (OIDS=FALSE); ``` I don't have any primary key here. I tried to delete using ``` DELETE FRO...
Try to prepare subquery with `LIMIT` as below ``` DELETE FROM txn_log WHERE txn_log_pgm_id IN (SELECT txn_log_pgm_id FROM txn_log ORDER BY txn_log_timestamp asc LIMIT 500) ```
``` DELETE FROM txn_log WHERE ctid IN ( SELECT ctid FROM txn_log ORDER BY txn_log_timestamp limit 500 ) ``` As per [Documentation](https://www.postgresql.org/docs/9.5/static/ddl-system-columns.html) > **ctid** > The physical location of the row version within its table. Note > that a...
How to delete first few records from a table without any criteria in PostgreSQL?
[ "", "sql", "postgresql", "" ]
I have created a stored procedure inside sql server 2008 r2, where i use to reference tables from 2 different Database that are defined inside the same sql instance as follow:- ``` [DB1].[dbo].[Technology] [DB2].[dbo].[SystemInfo] ``` currently we moved the DB2 to be on separate DB instance but at the same database...
If you mooved one database to other instance, then you should add that instance as linked server, call it like `[lnkDB]`, then you can query it like: ``` select * from [lnkDB].[DB2].[dbo].[SystemInfo] ``` Joins will not be different. You should only add servernane when referring to table from linked server.
I try to explain better writing the query. ``` SELECT * FROM [DB1].[dbo].[Technology] AS T INNER JOIN [Name_of_linked_server].[dbo][SystemInfo] AS S ON T.[KEY] = S.[KEY] ``` If the DB are different Server you need a Linked Server: <https://msdn.microsoft.com/EN-US/library/ff772782(v=sql.110...
join tables that are on different DB instance inside a stored procedure
[ "", "sql", "sql-server", "stored-procedures", "sql-server-2008-r2", "" ]
I have two tables with identical definition: ``` create tabA ( user_id int, contact boolean, promote boolean ); create tabB ( user_id int, contact boolean, promote boolean ); ``` I want to compare two columns `contact` and `promote` and see if there is any discrepancy in row data. For example: row from tabA: `1,T,T...
``` SELECT * FROM tabA, tabB WHERE tabA.user_id = tabA.user_id AND ( tabA.contact != tabB.contact OR tabA.promote != tabB.promote ); ```
As long as there can be NULL values, you need to use [null-safe operators](http://www.postgresql.org/docs/current/interactive/functions-comparison.html): ``` SELECT user_id, a.contact AS a_contact, a.promote AS a_promote , b.contact AS b_contact, b.promote AS b_promote FROM tabA a JOIN tabB b USING...
Compare two tables in postgres
[ "", "sql", "postgresql", "" ]
Given is a table of containers and their current location: ``` Date Container Location Scrapped --------------------------------------------- 2015/08/25 Container1 A 2015/08/25 Container2 B 2015/08/25 Container3 C 2015/08/26 Container1 D 2015/08/26 Container2 A 2015/08/26 Container3...
This one gives your expected results. [Demo fiddle is here](http://sqlfiddle.com/#!3/65f8d/37). ``` DECLARE @date DATE = '20150826' SELECT t1.[Date], t1.Container, (SELECT TOP(1) t2.Location FROM Table1 t2 WHERE t2.Container = t1.Container AND t2.[date] < t1.[date] ...
Try this and here is the [**SQL fiddle**](http://sqlfiddle.com/#!3/cfa82/28) ``` SELECT [Date] ,[Container] ,[From] ,[To] ,Scrapped FROM ( SELECT ct.DATE ,row_number() OVER ( PARTITION BY ct.Container ,ct.DATE ORDER BY frm.DATE DESC ) AS row_num ,...
Create query that contains movements out of destination list
[ "", "sql", "sql-server", "" ]
I have a `varchar` field like this `1-2-55-9` How can make a query to check if a number is in this field ? ``` select * from x where TEST ``` What test to do if For example `55 -> yes return record` , `5 -> no` , `7-> no`
I would just use **a `like` statement**. The syntax is standard SQL and therefor also applicable on other dbms like Oracle or SQL Server. ``` select * from x where (test like '%-55-%') or (test like '55-%') or (test like '%-55') ``` The like patterns use wildcards (i.e. `%`). The example above uses 3 conditions (in o...
Use [**`INSTR`**](http://www.w3resource.com/mysql/string-functions/mysql-instr-function.php) Function ``` select case when INSTR ('1-2-5-9', '5') > 0 then 'Yes' else 'No' End ``` **Update :** Use [**`FIND_IN_SET`**](http://www.w3resource.com/mysql/string-functions/mysql-find_in_set-function.php) Function. ``` SELEC...
Check if a number is in string delimited by seperator
[ "", "mysql", "sql", "" ]
First of all: It sounds pretty basic to me, but i did not find anything on this topic that comes close. I am using pl-sql and have a table thats contains records. Now i have created a new column and want to insert an entry when specific conditions given. Something like this ``` insert into myTable (newColumn) values ...
I think you want `update`, not `insert`: ``` updatE myTable set newColumn = newValue where oldColumn = 'something'; ```
Please use update query instead of insert as your table is ready with records and you have added a new column to existing table that is having values in it. syntax is as follows: ``` UPDATE new_column_name SET new_column_name='Dummy value' where (condition) ```
insert a single value into new created column
[ "", "sql", "oracle", "plsql", "sql-insert", "" ]
I've a column `email` in my table `person`, email column contains entries like ``` sam@yahoo.com xxxashish@gmail.com sunny@rediff.com xxxSomil@google.com ``` Now I want to update value of email column and remove all `xxx` from the begining of email id's. Any ideas how to achieve this? **Example**: `xxxashish@gmail.c...
try `UPDATE person SET email = RIGHT(email, LEN(email) - 3) WHERE email LIKE 'xxx%';` this way you wont replace `xxx` that might come in the text so `xxxladidaxxx@gmail.com` will return `ladidaxxx@gmail.com`
try ``` update person set email = REPLACE(email,'xxx','') where email like 'xxx%' ``` If xxx come in between email the above will replace that also.For that below code works ``` update person set email = RIGHT(email, LEN(email) - 3) where email like 'xxx%' ```
Update email field value in SQL
[ "", "sql", "sql-server-2008", "" ]
Notice the `2015-02` and `2015-03` months are missing in the output from the following group by `SQL`. If there is no data for a month I want to show the month and `0`. Anyone know how to go about this? ``` SELECT convert(char(7), MeterReadDate, 121),count(*) FROM [myTable] where (MeterReadDate > dateadd(d,-356,getdat...
If you don't want to go beyond your `min` and `max` dates of your results then you can do the following: ``` WITH cte AS ( SELECT convert(char(7), MeterReadDate, 121) AS [Date], COUNT(*) AS [Count] FROM [myTable] WHERE (MeterReadDate > dateadd(d,-356,getdate())) ...
You need a list of dates/months that covers the entire period. Here is one method using a recursive CTE: ``` with months as ( select cast(getdate() - 365) as thedate union all select date_add(1, month, thedate) from months where thedate <= getdate() ) select convert(char(7), m.thedat...
SQL select, pad with chronological missing months
[ "", "sql", "sql-server", "" ]
I have 4 tables : T1,T2,T3,T4 ``` --T1: Info_Id | fname | lname 101 | rol | lum --T2: Acc_id | acc_info_id | acc_property 01 | 101 | land --T3: Bill_id | status | amt_2_paid | Acc_id 123 | UNPAID | 200 | 01 --T4: Accnt_bill...
Just combine all your tables with one query using `INNER JOIN`. See below: ``` SELECT T1.fname, T1.lname, T3.status, T3.amt_2_paid FROM T1 INNER JOIN T2 ON T1.Info_id=T2.acc_info_id INNER JOIN T3 ON T2.Acc_id=T3.Acc_id INNER JOIN T4 ON T3. Bill_id=T4.Accnt_bill WHERE T4.[OR] ='01234' ```
``` SELECT fname, name, status,amt_2_paid FROM T3 INNER JOIN t4 ON t3.Bill_id = t4.Accnt_bill INNER JOIN t2 ON t2.Acc_id = t3.Acc_id INNER JOIN t1 ON t1.Info_id = t2.Info_Id WHERE t4."OR" = '01234' ```
How can I join 2 sub queries in postgresql?
[ "", "sql", "postgresql", "" ]
I have a stored procedure that returns 4 columns of data * Supporthoursworked (This is returned in minutes and multiplied to by 60) * SupportHoursCharged * DevelopmentHoursWorked (Also returned in minutes and multiplied) * DevelopmentHoursCharged My problem is that it currently returns those values in decimal form, a...
For `Sql Server 2012` and above: ``` SELECT timefromparts(SUM(SupportHoursWorked), 0, 0, 0, 0) ``` General: ``` SELECT DATEADD(hh, SUM(SupportHoursWorked), CAST('00:00:00' AS TIME)) ``` **EDIT:** Replace : ``` Select FromDate , SUM(SupportHoursWorked) AS SupportHoursWorked , SUM(SupportHoursCharged) ...
If you want it as standard date time, u can use this expression: ``` dateadd(mi,SUM(SupportHoursWorked)*60,'00:00') ``` If you want it "beautiful": ``` select CONVERT(VARCHAR(8), dateadd(mi,SUM(SupportHoursWorked)*60,'00:00'), 108) 'hh:mi:ss' ```
How can I convert decimals hours into hours and minutes in this procedure
[ "", "sql", "sql-server", "stored-procedures", "" ]
I'm trying to export the latest records from SQL Server 2005 database once weekly. This is my table: ``` agent_name date ID ALEX 2015-05-25 13 ALEX 2015-05-22 13 ALICE 2015-05-24 10 ALICE 2015-05-26 10 ``` How to create output table should like this: ``` agent_name da...
If you want latest rows for each `ID` and `agent_name` use this: ``` SELECT a.agent_name, MAX(a.[date]) [date], a.ID FROM Payment a GROUP BY a.agent_name, a.ID ``` --- If you want to have latest rows in each week use this: ``` SELECT a.agent_name, a.date, a.ID FROM (SELE...
This will return records from the first day of the current week to the last day of the current week ``` SELECT a.agent_name ,a.date ,a.ID FROM Payment a INNER JOIN agentmaster b ON a.ID = b.ID2 WHERE b.agent ='Y' AND (a.date BETWEEN DATEADD(wk, DAT...
How to get latest record weekly within an SQL statement
[ "", "sql", "sql-server", "date", "sql-server-2005", "" ]
My date is of type bigint. How can I select date? Typical query to get date is like this ``` select date from my_table where date<='20150101' ``` The problem right now is, date is of type bigint
The solution is just simple ``` select to_date(CAST(date as TEXT), 'YYYYMMDD') from my_table Where to_date(CAST(date as TEXT), 'YYYYMMDD')<=DATE '20141127' ; ```
Use: ``` select to_timestamp(date) from my_table where to_timestamp(date)<=DATE '2015-01-01' ```
convert bigint to date so that I can use in where clause
[ "", "sql", "postgresql", "" ]
I am trying to find the product EPC of the product which has the longest time between its first and last reading. There can be multiple entries in the table. For example, in the sample data shown below, one product with the EPC 03.0000A89... has a entry with date 1992-11-05, and one entry with date 2015-05-12. This ob...
So the EPC is your product code? Then you want the min and max time per EPC and then take the one with the max difference. That's all. ``` select epc from ( select epc, max(datetime) - min(datetime) as diff from track_record group by epc ) products order by diff desc limit 1; ```
It seems like a strange thing to want to know, but anyway... ``` SELECT EPC FROM track_record GROUP BY EPC ORDER BY DATEDIFF(MAX(datetime),MIN(datetime)) DESC LIMIT 1; +-----------------------------+ | EPC | +-----------------------------+ | 03.0000A89.00016F.000169DCD | +-------...
How to select column with greatest difference between dates in MySQL
[ "", "mysql", "sql", "database", "" ]
I need to query an `SQL` database to get all purchased products on last working date. For example, on `Monday` I need to get the records of `Saturday`. Also suppose due to some reason `Tuesday` is my leave I need to get the records of `Monday`. I tried my query like: ``` select ProductName , count(ProductName) as [No ...
Try this ``` select ProductName , count(ProductName) as [No Of Products],SUM(Total) as [TotalCost] from dbo.TransactionDetails where CurrentTime >=dateadd(day,datediff(day,1,(select MAX(CurrentDateTime) from CloseShifts)),0) AND CurrentTime <dateadd(day,datediff(day,0,(select MAX(CurrentDateTime) ...
`select ProductName , count(ProductName), SUM(Total), MAX(CurrentDateTime) from "dbo.TransactionDetails"` `inner join` with CloseShifts on your condition between two table (because you diid not provides the table)"
How to get records of last working day using sql server
[ "", "sql", "sql-server", "" ]
I have two temporary tables like below : TempEmploye ``` Name | Addres | Title SMITH |CALIFORNIA| Example1 WAYNE |BANDUNG | Example2 ROSE |PARIS | Example3 ``` TempTag ``` TAG | ValueTag | Desc AZ001 |Value1 | Desc1 AZ002 |Value2 | Desc2 AZ003 |Value3 | Desc3 ``` Then I want `join` b...
Since there is no common field to join two tables..u can use `Cross Join` ``` INSERT INTO tbResult (NAME, VALUETAG, DESC) SELECT e.Name, t.ValueTag t.Desc FROM TempEmployee e CROSS JOIN TempTag t ```
Try this: ``` INSERT INTO tbResult(NAME, VALUETAG, DESC) SELECT E.NAME,T.VALUETAG, T.DESC FROM #TempTag T CROSS JOIN #TempEmploye E ``` NOTE: Be careful trying to use `DESC` as column name because is SQL reserved word. If you have problems with `DESC` try to add `[]` as below ``` INSERT INTO tbResult(NAME, VALUETA...
INSERT INTO Table From Two Temporary Tables
[ "", "sql", "sql-server", "" ]
This is a follow-up question on [Sorting based on next and previous records in SQL](https://stackoverflow.com/questions/30477803/sorting-based-on-next-and-previous-records-in-sql) But now it gets a little more complex, for example: 1. If any letter of 1 matches any letter of 2, I want to change the ordering, so that ...
If I understand your requirement right, You have some parts of `parentId` and you want each part to start with the `letter`s those are in previous part And end with `letter`s those are in next part, If yes try this: ``` ;WITH t AS ( SELECT c.id, c.parentId, c.letter, dt.parentSeq ...
I am not sure if this will work for some complex real data, but you can check: ``` ;WITH cte AS(SELECT ci.id, ci.parentId, ci.letter, p.number, DENSE_RANK() OVER (ORDER BY p.number) rn FROM Child ci JOIN Parent p ON ci.parentId = p.id) SELECT t1.number, t1.letter FROM ...
Complex sorting based on next and previous records in SQL
[ "", "sql", "sql-server", "sql-server-2005", "sql-order-by", "" ]