Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
``` CommentID Name Replies OrderID 313 Ed dlfkndl sdknldgf dlffdg 496 313 James sdsflsdf snflsf sfnslf sfnklsdf 499 313 Jeff sdsflsdf snflsf sfnslf sfnklsdf 500 313 Alan sdsflsdf snflsf sfnslf sfnklsdf...
You can also write the query using `Common Table Expression` as: ``` With CTE as ( select row_number() over ( partition by CommentID order by OrderID desc) as rownum, CommentID, Name, Replies, OrderID From reptab ) select CommentID, Name, Replies, Or...
Selecting the bottom 3 records in a subquery ordered descending, then order the outer ascending. ``` Select * from (select top 3 orderid, commentid, replies, name From [RepTab] Order by orderid desc ) t Order by order id ``` ## [fiddle](http://sqlfiddle.com/#!3/93692/1)
fetching last 3 rows in ascending order with t-sql?
[ "", "sql", "sql-server", "t-sql", "" ]
I have SP that has a parameter @NumeroTransferencia int. I need to select rows that match that variable when it is not null. But when it's null, I have to return the ones which have H.CodigoTransferencia = null I tried the following but I didn't get a good result: ``` SELECT * FROM RUTEO.HOJADERUTA H WHERE (H.Co...
``` SELECT * FROM RUTEO.HOJADERUTA H WHERE ((H.CodigoTransferencia IS NULL AND @NumeroTransferencia IS NULL) OR H.CodigoTransferencia = @NumeroTransferencia) ```
You can try this ``` SELECT * FROM RUTEO.HOJADERUTA H WHERE (@NumeroTransferencia IS NULL AND H.CodigoTransferencia IS NULL) OR (@NumeroTransferencia IS NOT NULL AND H.CodigoTransferencia = @NumeroTransferencia) ```
SQL Server: WHERE clause with null comparison
[ "", "sql", "null", "case", "where-clause", "" ]
I am looking at a checklist that contains several unique checklist items. I only want to select records (ID, name, etc) of those who have NO null values in the checklist date field. ``` Select distinct sp.id as "ID", SP.LAST_NAME as "Last", SP.FIRST_NAME as "First", SA.T...
``` WITH MYVIEW AS ( Select sp.id as ID, SP.LAST_NAME , SP.FIRST_NAME, SA.TERM_CODE_ENTRY, SA.APST_CODE, CK.SARC_RECEIVE_DATE As RECEIVED_DATE FROM SPRITE SP JOIN SARC CK on sp.sprite_pidm = CK.SARC_pidm JOIN ADAP SA on...
You wouldn't do it that way. Instead, use an analytic function to count the number of NULL values and choose the ones that don't have any. Here is the idea: ``` with t as ( <your query here> ) select * from (select t.*, sum(case when SARC_RECEIVE_DATE is null then 1 else 0 end) as numNulls from t ...
oracle sql - Select ONLY if there are NO null values in that column
[ "", "sql", "oracle", "notnull", "" ]
I want to retrieve a full table with some of the values sorted. The sorted values should all appear before the unsorted values. I though I could pull this off with a UNION but order by is only valid to use after unioning the table and my set of data isn't set up such that that is useful in this case. I want rows with a...
You could do something like this: ``` order by (case when currentValue <= 6 then 1 else 0 end) desc, (case when currentValue <= 6 then column end) desc ``` The first puts the values you care about first. The second puts them in sorted order. The rest will be ordered arbitrarily.
Try this: ``` SELECT * FROM yourdata ORDER BY CASE WHEN yourColumn BETWEEN 0 AND 6 THEN yourColumn ELSE -1 End Desc ```
SQL Order By Except When You Don't
[ "", "sql", "sql-order-by", "" ]
How to find out a Sundays in a month? please help me on this.. no of Sundays : 4 for current month and i need to subtract these count from the days in a month :: days in a month -sundays If i pass the dates in between from and to i need to get the count of sundays for that period.. Many thanks for your help. Suni...
Try this: ``` select to_char(last_day(sysdate),'dd') - ((next_day(last_day(trunc(sysdate)),'sunday')-7 -next_day(trunc(sysdate,'mm')-1,'sunday'))/7+1) as result from dual ``` For count dates between a period you can do this: ``` SELECT (next_day(TRUNC(TO_DATE('28/09/2014','DD/MM/YYYY')),'sunday') - n...
If you have from and to dates, you should first generate all the dates between them using hierarchal query. And then filter only sundays from them. ``` select count(1) from ( select start_date + level - 1 as dates from dual connect by start_date + level - 1 <= end_date ) where to_char(dates,'fmday') = 'sun...
how to subtract the Sundays from no of days in a month
[ "", "sql", "oracle", "" ]
I want to sort records as follows: 1. Future/present events ASC 2. Past events DESC So first today, then tomorrow, until there are no more future records. Then I want to show the past events, but the latest first. So far I've found a solution for the first point: ``` ORDER BY ( CASE WHEN ev.StartDate < CURDATE(...
You need a slightly more complex `order by`: ``` ORDER BY (ev.StartDate < CURDATE()), (case when ev.StartDate > CURDATE() then ev.StartDate end) ASC, (case when ev.StartDate < CURDATE() then ev.StartDate end) DESC ``` You could actually do this with two clauses: ``` ORDER BY greatest(ev.StartDate, ...
I find this most straight forward, without needing complex conditional syntax: first one ranks future before past, second one orders the future ASC, third one orders the past DESC (second and third ones are interchangeable) ``` ORDER BY (date < CURDATE()) ASC, (greatest(date, CURDATE()) ASC, (least(date, CURDA...
Sort records by; future ASC, past DESC
[ "", "mysql", "sql", "" ]
I have a database in which there is a column named "codes". When this column of codes is displayed in gridview I would like to modify the contents of the column. For example: In Database if the codes column contains A,B and C values, then in gridview it should show Abeloth(instead of A), Bollux (instead of B), Chewbac...
I was able to solve this issue by using GridView.RowDataBound event. Few articles that helped me are 1) [MSDN](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowdatabound(v=vs.110).aspx) 2) [Question on StackOverflow](https://stackoverflow.com/questions/11671905/how-to-change-in-a-gridview...
one way to achieve this is using "itemdatabound" event for the gridview control and then decide what values you'd rather display in the gridview with respect to the actual values in the database table.
Modify data from database to gridview
[ "", "sql", "vb.net", "gridview", "" ]
I have a sample table like below where Course Completion Status of a Student is being stored: ``` Create Table StudentCourseCompletionStatus ( CourseCompletionID int primary key identity(1,1), StudentID int not null, AlgorithmCourseStatus nvarchar(30), DatabaseCourseStatus nvarchar(30), NetworkingC...
vou could also consider storing results in flat table like this: ## studentID,courseID,status * 1,1,"completed" * 1,2,"not started" * 2,1,"not started" * 2,3,"in progress" you will also need additional Courses table like this ## courserId,courseName * 1, math * 2, programming * 3, networking and a students table ...
> but now 5 rows are required No, it's still just one row. That row simply contains identifiers for values stored in other tables. There are pros and cons to this. One of the main reasons to normalize in this way is to protect the integrity of the data. If a column is just a string then anything can be stored there. ...
Database Normalization using Foreign Key
[ "", "sql", "sql-server", "database-normalization", "" ]
I have a order table that contains and order number, customer id and agent id. Then theres a customer table with a id and a agent table with a id. I need to get all the customer ids that have an order from both agent id 'a03' and agent id 'a05' Right now I'm trying to get all the customer ids but only the ones that a...
It sounds like you want to return only those customers who appear for both agents. If that is the case, then you can use group by: ``` select c.cid from customer c join order1 o on c.cid = o.cid join agent a on o.aid = a.aid where a.aid in ('a05','a03') group by c.cid having count(distinct a.aid) = 2 ```
You need to replace `and` with `or customer.cid in`: ``` select customer.cid from customer where customer.cid in (select order1.cid from order1 inner join agent on order1.aid=agent.aid where agent.aid="a05") or customer.cid in (select order1.cid from order1 inner join agent on...
MySQL chaining WHERE IN
[ "", "mysql", "sql", "" ]
Is there a way to use intersect without selecting distinct values only? Something like `INTERSECT ALL`. For example, consider table A and B ``` A --> 1, 1, 1, 2, 3, 4 B --> 1, 1, 2 ``` Would result in ``` Result --> 1, 1, 2 ``` **EDIT** I think this [link](http://www.freelists.org/post/oracle-l/Except-Minus-all-...
In SQL Server, `INTERSECT` works on distinct rows only. If you want it to distinguish between duplicate rows, you will need to make the rows distinct. The only way to do so I can think of is to add another column and populate it with unique values per duplicate, but in such a way that the resulting rows would be matcha...
``` SELECT COLUMN1 FROM B WHERE B.COLUMN1 IN (SELECT COLUMN1 FROM A) ```
Intersect in SQL Server
[ "", "sql", "sql-server", "intersect", "" ]
I have a rather complex and time consuming query which returns a result set with two columns like this: ``` | ID1 | ID2 1 10 2 11 3 15 ``` I want to have those results in one column: ``` | ID 1 10 2 11 3 15 ``` Is this possible in (oracle) sql? The (simplified) query looks like th...
``` with source as ( SELECT adr.nad_nkt_id id1, firmenadr.nad_nkt_id id2 FROM nav_adressen adr, nav_kontakte kontakt, nav_kontakte firma, nav_adressen firmenadr WHERE kontakt.nkt_id = adr.nad_nkt_id AND firma.nkt_id (+)= kontakt.nkt_nkt_id AND firmenadr.nad_id (+)= firma.nkt_id AND (firmenadr.nad_str...
You're after a `UNION`: ``` SELECT ID1 FROM YourTable UNION SELECT ID2 FROM YourTable ``` `UNION` will return distinct items, `UNION ALL` will return all items (and is therefore faster). Given the amount of filtering/joining you're doing, it makes sense to do the filtering first into a temp table then run the `UNIO...
How to make two rows out of one
[ "", "sql", "oracle", "oracle11g", "" ]
I want the OrderType for the min(Date) for each Name. So, I want this: ``` Name Date OrderType Alex 1/1/2014 Direct Alex 9/15/2014 Distributor Cindy 6/4/2014 Distributor John 5/8/2014 Direct John 2/14/2014 Distributor ``` to return this: ``` Name Date OrderType Alex ...
We can get row number based on the date for each `[Name]` and pick the least date record. ``` SELECT [T].* FROM ( SELECT [Name] , [DATE] , [OrderType] , ROW_NUMBER() OVER (PARTITION BY [Name] ORDER BY [Date]) AS [seq] FROM [TableA] ) AS [T] WHERE [T].[seq] = 1 ```
I think you need select the min date per person then join back to the original table to get the type for that row. Assuming your table is called tab and each person only had one order per date (otherwise the question is impossible) then something like: ``` Select t.name, t.date, t.ordertype From tab t, ( select ...
sql select min, return value from different column in same row with grouping
[ "", "sql", "sql-server", "t-sql", "" ]
I'd like to select each pair of two columns in a database, but only select the entry with the lowest price. As a result, I want to output the `id` and the `price` column. But it does not work: My table: ``` id | category | type | name | price 1;"car";"pkw";"honda";1000.00 2;"car";"pkw";"bmw";2000.00 ``` SQL: ``` s...
If you want the entry with the lowest price, then calculate the lowest price and join the information back in: ``` select ct.* from cartable ct join (select category, type, min(price) as price from cartable group by category, type ) ctp on ct.category = ctp.category and ct.type = ctp.type an...
You can achieve this with EXISTS clause: ``` SELECT * FROM cartable ct WHERE NOT EXISTS ( SELECT * FROM cartable WHERE ct.type = type and ct.category = categoery and ct.price < price) ``` For speed caparison can you try this: ``` SELECT DISTINCT ON (type, category), id, pric...
How to select records with minimum price per group
[ "", "sql", "database", "postgresql", "greatest-n-per-group", "" ]
I'm new to this so please bear with me. I'm writing a query where I need to count the number of rows with two specific values, I have used the following to get the result of the different values in one field but I need to know the results only if another field is set to a specific value. I pulled the following from a...
You can just add the condition into the `where` clause: ``` COALESCE(count(case when CW.MAINJOBROLE = 2 and CW.EMPLSTATUS = 1 THEN 1 end),0) as ALLJOBROLES_2, ``` By the way, the `COALESCE()` should be unnecessary. `COUNT()` will return `0` if there are no matches.
You will have to surround each expression with another CASE WHEN construct: ``` CASE WHEN CW.EMPLSTATUS = 1 THEN count(case when CW.MAINJOBROLE = 2 THEN 1 end) ELSE NULL END as ALLJOBROLES_2, CASE WHEN CW.EMPLSTATUS = 1 THEN count(case when CW.MAINJOBROLE = 3 THEN 1 end) ELSE NULL END as ALLJOBROLES_3, .... ``...
Bringing together coalesce, count, case and clauses
[ "", "sql", "coalesce", "" ]
Are PL/SQL stored procedures transactions? When a trigger, procedure or function runs, is it a transaction? I usually end my procedures with `COMMIT` and when an error occurs I use `ROLLBACK`! Is it wrong? I'am not asking about `START TRANSACTION` into procedures but I want to know if they are transactions. Thank you...
`Are PL/SQL stored procedures transactions? When a trigger, procedure or function runs, is it a transaction?` No. A transaction starts with the first DML encountered and ends when it encounters a COMMIT or ROLLBACK. A transaction can comprise many function and procedure calls and DML statements and trigger code. On th...
Off course its not a transaction but a modification. And you dont need to specify Commit everytime to save your transaction. In Oracle for example all individual DML statements are atomic (i.e. they either succeed in full, or rollback any intermediate changes on the first failure) (unless you use the EXCEPTIONS INTO op...
Are PL/SQL stored procedures transactions?
[ "", "sql", "database", "oracle", "stored-procedures", "transactions", "" ]
this is the first time I've tried including a row count within a select statement. I've tried the following but including `COUNT(other row)` is apparently not allowed in the way I'm trying to do it. How can I include a row count from another table in a select statement, mainly consisting of objects from the first table...
You are missing your `GROUP BY`. Whenever you aggregate (`SUM`, `COUNT`, `MAX`, etc..) you always need to include a `GROUP BY` statement that includes all visible fields except your aggregated fields. So your code should read: ``` SELECT Reports.ReportID, EmployeeADcontext, ReportName, CreatedDate, COUNT(Expenses.ExpI...
You need a group by clause. Add: ``` GROUP BY Reports.ReportID, EmployeeADcontext, ReportName, CreatedDate, ReportTotal, Status ```
How can I COUNT rows from another table using a SELECT statement when joining?
[ "", "sql", "t-sql", "stored-procedures", "" ]
Hi I am new to sql and stuck in a problem. Below is the sample of my table. This is not the exact table but a sample of what i am trying to achieve ``` Name Classification Hits A A1 2 A A2 3 A A3 4 A A4 8 A A5 ...
You can use a CTE with the `Row_Number()` function ``` ;WITH CTE AS( SELECT Name, Classification, Hits, Row_Number() OVER(Partition by name ORDER BY Hits DESC) AS RowNum FROM Table4 ) SELECT Name, Classification, Hits FROM CTE WHERE RowNum <= 2 ORDER BY Name, Hits ``` [...
I'm working from memory so I'm not sure of the syntax, and there's probably a more efficient way to do this, but you'd want to do something like ``` ;with rawdata as ( select Name, Classification, Hits, Row_number() over (partition by Name order by Hits desc) as x ) select Name, Classification, Hits from...
Sql Getting Top 2 results in each classification
[ "", "sql", "sql-server", "sql-server-2008", "" ]
In one case, we have to store values for +infinity & -infinity in a Postgres DB? What should be appropriate value that should be considered? If there is not one, then please suggest the best suitable alternative.
You can actually use `+infinity` and `-infinity` for `FLOAT4` and `FLOAT8` (i.e. `float` and `double precision`) data types, and for timestamps. ``` regress=> SELECT FLOAT8 '+infinity', FLOAT8 '-infinity'; float8 | float8 ----------+----------- Infinity | -Infinity (1 row) ``` For other types, either use a se...
You can insert the string `'infinity'` or `'-infinity'` into a **numeric/float/real/double precision** column types. However, this will be *out of range error* for **integer/bigint/smallint**. * `'+infinity'` and `'infinity'` and `'Infinity'` are equivalent * `'-infinity'` and `'-Infinity'` are equivalent Some exampl...
Appropriate values for -Infinity & Infinity in Postgres
[ "", "sql", "postgresql", "" ]
My SQL Server database has many tables with variety of data types being used. The current design has a standard datatype length for columns ex: `NVARCHAR` like 200, 1000 or MAX (this is a standard we are adopted) depending on what type of data I saved, I use datatype accordingly. For a `NAME` column I believe it does ...
Generally I tend to use the smaller types whenever I can, but it's not always possible or convenient, and there are certainly trade-offs in each choice. For one, 200 don't seems a disparate amount but if the data is guaranteed to be limited at 75 chars a smaller type is perhaps a better option. I would analyze the pros...
I always try to keep the data type and size realistic. I do think 200 is way too much and why Nvarchar? I think Varchar(50) or 75 as you think is suffice. It does have an impact on application if you were to create class because an application would have to reserve the byte size causing an application to require more m...
Database column data type
[ "", "sql", ".net", "sql-server", "database", "" ]
I have a table example like this: ``` date id status 01/01/2013 55555 high 01/01/2014 55555 low 01/01/2010 44444 high 01/01/2011 33333 low ``` I need in order: `group by id` and select most recent date. this is the result I want. ``` date id status 01/01/2014 55555 low 01/...
you need to join your table with a subquery that "links" the record date with the greatest date for each id: ``` select a.* from your_table as a inner join ( select id, max(date) as max_date from your_table group by id ) as b on a.id = b.id and a.date = b.max_date; ```
I think you will need a subquery to get the MAX(Date) and then inner join. Try this: ``` SELECT A.[Date], A.[Id], A.[Status] FROM Table A INNER JOIN(SELECT Id, MAX([Date]) AS MaxDate FROM Table GROUP BY [Id]) B ON A.[Id] = B.[Id] AND A.[Date] = B.[MaxDate] ```
Group by id and select most recent
[ "", "sql", "ms-access", "group-by", "" ]
I'm currently selecting Material from two tables using a `union` operator: ## **QUERY** ``` SELECT Material FROM ( SELECT Material FROM DP_Historical_Data EXCEPT SELECT Material FROM SAS_GLOBE_Material_to_SASBaseItem ) HD UNION SELECT Material FROM ( SELECT Material ...
``` Select UnionResult.Material, DT.MaterialDescription FROM Description_Table DT JOIN ( SELECT Material FROM ( SELECT Material FROM DP_Historical_Data EXCEPT SELECT Material FROM SAS_GLOBE_Material_to_SASBaseItem ) HD UNION SELECT Material FROM ...
``` SELECT DT.MaterialDescription FROM Description_Table DT INNER JOIN ( SELECT Material FROM ( SELECT Material FROM DP_Historical_Data EXCEPT SELECT Material FROM SAS_GLOBE_Material_to_SASBaseItem ) HD UNION SELECT Material FROM ( SELECT M...
Select from a third table based upon a union result
[ "", "sql", "sql-server", "" ]
So I have achieved the results I want, but want to know if there is a better / cleaner way to do it: ``` SELECT * from Services LEFT JOIN SellerServices ON SellerServices.Type = Services.Type WHERE `id` =$user_id OR Services.Type NOT IN ( SELECT SellerServices.Type FROM SellerServices where id ...
If your query returns the expected result, here is the same query with juste few adjustments (may be more performant): ``` SELECT S.* ,CASE WHEN S.id = $user_id THEN 'ON' ELSE 'OFF' END AS is_user FROM Services S LEFT JOIN SellerServices SS ON SS.Type = S.Type LEFT JOIN SellerServices SSU ON SSU....
Do you want something like this? ``` select s.*, (exists (select 1 from SellerServices ss on ss.Type = s.type) ) as ExistsFlag from services s where s.id = $userid; ``` This chooses all rows (and columns) form `services`. It adds a boolean if the `type` exists in the second table.
SQL getting one of each entries from left table and treating existence in the right as a boolean
[ "", "mysql", "sql", "lamp", "" ]
Sorry, I asked this question just before and got some good answers but then I realised I made a mistake with the query in question, if I change the question in the original post that could make the answers invalid so I'm posting again with the right query this time, please forgive me, I hope this is acceptable. ``` DE...
Sure can. I might start with combining the two queries from your inserts using `UNION ALL` (this variation of `UNION` will not remove duplicates), wrapped up in a [CTE](http://technet.microsoft.com/en-us/library/ms190766(v=sql.105).aspx) from which you can perform your final query: ``` WITH MeasureData(MeasureDate, co...
No real need for a `UNION`, you can handle this with a `CASE` statement: ``` SELECT SUM(col1) / SUM(col2) AS Percentage, MeasureDate, Type FROM ( SELECT MeasureDate, col1, col2, case when Col4 = 7000 then 3 else 1 end type FROM Table1 WHERE Col3 = 1 ) t GROUP BY MeasureDate, Type ``` --- Edit, as Gordon...
merge two queries with different where and different grouping into 1
[ "", "sql", "t-sql", "stored-procedures", "" ]
trying to write a sql which will keep first N number of rows of a table and delete the rest. I'm have comeup with this sql but the its saying I can't use the count here. Please help me to re write the sql. ``` DELETE FROM ZZ_TEST_FINTABLE WHERE PROCESS_INSTANCE = ( SELECT MIN(B.PROCESS_INSTANCE) FROM ZZ_TEST_...
Maybe this works for you (with Oracle DB) ``` DELETE FROM ZZ_TEST_FINTABLE WHERE PROCESS_INSTANCE NOT IN ( SELECT PROCESS_INSTANCE FROM ZZ_TEST_FINTABLE WHERE ROWNUM < 9 ); ```
You should use HAVING instead of AND. ``` DELETE FROM ZZ_TEST_FINTABLE WHERE PROCESS_INSTANCE = ( SELECT MIN(B.PROCESS_INSTANCE) FROM ZZ_TEST_FINTABLE B ) HAVING COUNT(PROCESS_INTANCE) > 9 ``` or this ``` DELETE ...
Keep First N number of rows and delete the rest
[ "", "sql", "db2", "udb", "" ]
Scenario: I have 2 query form 1 table, just want to view both query results as a single query result. Details: Table: loantrans ``` +-----+----------+---------+---------+---------+ | tid | date | account | purpose | out | +-----+----------+---------+---------+---------+ | 1 |2014-08-12| 975 | Loan | ...
``` SELECT MONTH(lt.date) month, SUM( case when lt.purpose='Interest' then lt.out else 0 end) intout, SUM(case when lt.purpose='Loan' then lt.out else 0 end) loanout FROM loantrans lt WHERE lt.date BETWEEN '2014-01-01' AND '2014-09-20' GROUP BY month ORDER BY month ``` <http://sqlfiddle.com/...
``` SELECT MONTH(lt.date) month, SUM((lt.purpose='Interest')*lt.out) intout, SUM((lt.purpose='Loan')*lt.out) loanout FROM loantrans lt WHERE lt.date BETWEEN '2014-01-01' AND '2014-09-20' /* AND lt.purpose IN ('Interest', 'Loan') /* If you have more purposes. */ GROUP BY month ORDER BY mo...
How to join 2 query results together?
[ "", "mysql", "sql", "" ]
Why does the @result value in the code below print out a blank string? I would expect it to concatenate with the previous result. ``` DECLARE @size int DECLARE @string nvarchar(10) DECLARE @result nvarchar(10) SELECT @string = '12345abc123' DECLARE @count int, @total int SELECT @total = LEN(@string), @count =...
You never initialized `@result`, so it defaults to an sql `null`. SQL nulls are contagious poison, so when you do ``` SELECT @result = .... + @result ``` You're actually doing ``` SELECT @result = ... + null ``` and `@result` simply remains `null` Initializing the value to an empty string solves your problem: ```...
It is returning a blank because you are concatenating the substring with @result, which initially is NULL. Try setting @result to an empty string like this this: ``` SELECT @string = '12345abc123', @result = '' ```
Why does this TSql return a blank or null value?
[ "", "sql", "t-sql", "" ]
``` | iID | saleID | cusID | date | total | discount | advance | paid_status | +-----+--------+-------+------------+-------+----------+---------+-------------+ | 16 | 1 | 1 | 2014-01-17 | 2400 | 100 | 1000 | 1 | | 17 | 1 | 1 | 2014-02-17 | 240 | 100 | 1000 | ...
Please use `where` before `group by` <http://dev.mysql.com/doc/refman/5.0/en/select.html>
Try moving the `group by` statement to the end of the command
mysql where clause give me an error
[ "", "mysql", "sql", "group-by", "where-clause", "" ]
I have three var char values as ``` @hour = '18' @minute = '25' @seconds = '45' ``` I need output in the form of '18:25:45' ``` Select from Convert(Time,@hour+@minute+@seconds) ``` values in hour minute and seconds coming from SSRS report drop down
An implicit conversion is not allowed. One solution could be to organise the format as a string and then convert to time as below. ``` declare @hour smallint = '18' declare @minute smallint = '25' declare @seconds smallint = '45' declare @format varchar(8) = (select (CAST(@hour as varchar(2)) + ':'+ CAST(@minute as v...
You can 'add-up' the values from zero, like this: ``` declare @hour smallint = 18 declare @minute smallint = 25 declare @seconds smallint = 45 declare @result time SELECT @result = DATEADD(hour, @hour, DATEADD(minute, @minute, DATEADD(second, @seconds, 0))) ```
How to create Time with Hour+Minute+Seconds in sql server 2008
[ "", "sql", "sql-server-2008-r2", "" ]
I have 2 tables with duplicated values in one of the columns. I'd like to do a left join without taking rows, where mentioned column values duplicates. For example, i have table X: ``` id Value A 2 B 4 C 5 ``` and table Y: ``` id Value A 2 A 8 B 2 ``` I'm doing a LEFT JOIN: ``` SELECT* FROM X LEFT JOIN...
You can do it with `GROUP BY`: ``` SELECT X.id, X.value, MIN(Y.value) FROM X LEFT JOIN Y ON X.id = Y.id GROUP BY X.id, X.value ``` Note that it is not necessary to bring `Y.id` into the mix, because it is either `null` or equal to `X.id`.
You are looking for GROUP BY to aggregate the Y table records, effectively collapsing them down to one row per id. I have chosen MIN but you could use SUM if they are integers like your example data. ``` SELECT x.id , x.Value, y.id, min(y.value) FROM X LEFT JOIN Y ON X.id = Y.id GROUP BY x.id, x.value,...
How to do a LEFT JOIN in MS Access without duplicates?
[ "", "sql", "ms-access", "ms-access-2010", "left-join", "" ]
Say you have a non-relational table `Persons` that is filled with badly formatted data: Persons: ``` id name city state country ('1', 'username1', 'Cityville', 'Alabama', 'USA') ('1', 'username1', 'Cityville', 'Alabama', 'USA') ('2', 'username2', 'Cityville', 'Alabama', 'USA') ('2', 'username2...
I dont think you need to do a UNION ALL here I think it should be something like this... ``` INSERT INTO Clean_Persons (user_ID, Loc_ID) SELECT DISTINCT TO_NUMBER(P.USER_ID), L.loc_ID FROM Location L JOIN Persons P ON ( L.city = P.city AND L.state = P.state AND L.country = P.country ); ```
You don't need `UNION`, but rather just a `JOIN`: ``` INSERT INTO Clean_Persons (Id, Name, Loc_Id) SELECT DISTINCT TO_NUMBER(P.Id), P.Name, L.Loc_Id FROM Persons P JOIN Location L ON P.City = L.City AND P.State = L.State AND P.Country = L.Country ``` Given the duplicated data in the `Persons` t...
INSERT from UNION of 2 selects?
[ "", "sql", "oracle", "" ]
I got query like this ``` SELECT IMAGE_PATH, IMAGE_ID, DOC_NID FROM TBL_IMAGE WHERE IMAGE_ORD = 1 ``` And have follow conditions * image\_ord should br changed to image\_ord=max value * image\_ord column is number type and it has some duplication * I need only one row with biggest value of image\_ord * it coul...
Based on your requirements: > "image\_ord [...] has some duplication" > > "I need only one row with biggest value of image\_ord" ``` WITH C AS ( SELECT MAX(IMAGE_ORD) M FROM TBL_IMAGE ) SELECT TBL_IMAGE.IMAGE_PATH, TBL_IMAGE.IMAGE_ID, TBL_IMAGE.DOC_NID FROM TBL_IMAGE JOIN C ON IMAGE_ORD = C.M WHERE ROWNUM < 2 `...
Try this : ``` SELECT IMAGE_PATH, IMAGE_ID, DOC_NID, Max(image_ord) FROM TBL_IMAGE WHERE IMAGE_ORD = 1 group by IMAGE_PATH, IMAGE_ID, DOC_NID ```
How can I get a row which has biggest value?
[ "", "sql", "oracle", "sql-order-by", "max", "limit", "" ]
I have a query that selects the oldest record from table B, which contains multiple rows for each row in table A, and joins it to table A: ``` SELECT A.Surname, A.Fornames, A.DOB, (SELECT TOP 1 B.RegNumber FROM B WHERE B.ID=A.ID ORDER BY B.Date ASC) AS RegNumber FROM A ORDER BY A.Surname; ``` This works gr...
You have two options, the first is to restructure your query using joins: The principle is, you need to get the first date for each record in `B` grouped by `ID`: ``` SELECT ID, MIN(Date) AS [FirstDate] FROM B GROUP BY ID; ``` You can then JOIN this back to B, to filter the results, i.e.: ``` SELECT B.* FROM ...
You can repeat the subquery: ``` SELECT A.Surname, A.Fornames, A.DOB, (SELECT TOP 1 B.RegNumber FROM B WHERE B.ID=A.ID ORDER BY B.Date ASC ) AS RegNumber, (SELECT min(b.Date) FROM B WHERE B.ID=A.ID ) AS RegDate FROM A ORDER BY A.Surname; ```
Selecting more than one column in subquery
[ "", "sql", "ms-access", "" ]
I have a situation to handle, i have my liquibase structured as per the best practices recommended. I have the change log xml structured as given below ``` Master XML -->Release XML -->Feature XML -->changelog XML ``` In our application group, we run updateSQL to generate the consolidated sql file a...
You would be able to write an extension (<http://liquibase.org/extensions>) that injects it in. If you need to do it per changeLog, it may work best to extend XMLChangeLogParser to automatically create and add a new changeSet that runs the needed SQL.
You could make a changeSet with the attribute 'runAlways' set to true and include the SQL.
executing a common sql file using liquibase
[ "", "sql", "oracle", "liquibase", "changelog", "" ]
I have the following table *test* ``` +----+---------+------+ | Id | NumFact | type | +----+---------+------+ | 1 | 20 | A | | 2 | 21 | A | | 3 | 22 | A | | 4 | 23 | B | | 5 | 24 | B | | 6 | 25 | B | | 7 | 26 | B | | 8 | 26 | T | +----+---------...
You just need to group by `type` and filter properly. ``` SELECT type, COUNT(NumFact) AS Num FROM test WHERE type IN ('A','B') GROUP BY type; ``` What this says is to group the result set the column `type` and use the aggregate function `COUNT()` for each group but only where the `type` column value is equal to 'A' o...
Use `GROUP BY` ## **Query1** ``` SELECT COUNT(NumFact) AS Num, type FROM test WHERE type IN ('A','B') GROUP BY type ``` ## **Query2** ``` SELECT COUNT(NumFact) AS Num, type FROM test WHERE type='A' OR type='B' GROUP BY type; ``` --- ## [DEMO](http://sqlfiddle.com/#!3/ecb44/5)
Combine two select
[ "", "sql", "sql-server", "dml", "" ]
In my MySql table there's a column called \_time of type varchar. The values it holds are in the format: `year month day hour minute` without the whitespaces: `201409201945` I want to convert it to `datetime` so I'm doing this: ``` ALTER TABLE `my_table` CHANGE COLUMN `_time` `date_time` DATETIME NOT NULL; ``` And it...
The three steps @Arkain mentioned would be with the help of the function [STR\_TO\_DATE](http://dev.mysql.com/doc/refman/5.6/en/date-and-time-functions.html#function_str-to-date) ``` -- add the new column ALTER TABLE `my_table` ADD COLUMN `date_time` DATETIME; -- update the new column with the help of the function S...
If your `varchar` data were formatted like this '2014-09-20 19:45' altering your column's data type would work. Why? that's the character representation used by `DATETIME` and other time-oriented data types. But it isn't. So, what choices do you have? One is to use these four steps: 1. alter the table to add a new `D...
Unable to convert varchar to datetime in MySql
[ "", "mysql", "sql", "datetime", "datetime-format", "" ]
I have a query like this. ``` select ad.escore, ad.mscore, round(sum(ps.cnt) / sum(n.cnt) * 100,1) as percent from ( select account_no, -- 602 becomes '595-604' to_char(trunc(empirica_score - 5, -1) + 5, '9999') || '-' || to_char(trunc(empirica_score - 5, -1) + 14, '9999') as escore, -- 97 b...
Well, *this* bit won't work: ``` select customer_code, count(distinct start_date) as cnt from naedo and start_date >= '13/08/2014' <------- HERE and start_date <= '12/19/2014' <------- HERE group by ... ``` since the `where` clause has to start with a `where`, not an `and`. Otherwise, we'd all be calling i...
``` select customer_code, count(distinct start_date) as cnt from naedo Where start_date >= '13/08/2014' <------- HERE and start_date <= '12/19/2014' <------- HERE group by customer_code ```
ERROR: syntax error at or near "and"
[ "", "sql", "postgresql", "" ]
I have a MySQL dataset that looks like this: ``` a b .32 .72 .41 .80 .28 .64 .31 .80 ``` And I want to assign values (*c*) to each row based on the conditions of a and b: .3 < a < .4 and .71 < b < .83 = 1 .4 < a < .5 and .71 < b < .83 = 2 .2 < a < .3 and .58 < b < .77 = 3 and so on. This would result ...
I don't fully understand this: *I have tried a case when() statement but that didn't work since I don't know how/if it is possible to have one of those with more than one case.* This will get you the output you described however. I'm a bit lazy/tired so I'll just paste the output from SQL Fiddle: [SQL Fiddle](http://...
I would create a secondary table and use it to drive the update. Generally, try to parametrize things like this into tables, rather than making a big honking sql. That still leaves you with the question of whether there is a contradiction in your criteria (i.e. multiple outcomes possible, no outcomes, etc...) but is ...
Assign integer value to row based on interval - SQL
[ "", "sql", "" ]
I have the following select statement: ``` SELECT * FROM pgp WHERE group_id IN ( SELECT group_id FROM pgroups WHERE label LIKE 'Registration%' AND label NOT LIKE '%Snom%' ) AND pid = 12; ``` it returns results like: ``` group_id | pid | value | updatev ----------+----------+-------+----...
Just change the `SELECT` to an `UPDATE`: ``` UPDATE pgp SET updatev = 't' WHERE group_id IN (SELECT group_id FROM pgroups WHERE label like 'Registration%' and label not like '%Snom%') and pid = 12; ``` That's actually a good practice - get your criteria right with a `SELECT` before actually changing any data.
Use an [`update`](http://www.postgresql.org/docs/9.2/static/sql-update.html) statement: ``` UPDATE pgp SET updatev = true WHERE group_id IN (SELECT group_id FROM pgroups WHERE label LIKE 'Registration%' AND label NOT LIKE '%Snom%') AND ...
how to select records from table A and update table A
[ "", "sql", "postgresql-9.2", "" ]
Say I have a table Clients, with a field ClientID, and that client has orders that are loaded in another table Orders, with foreign key ClientID to link both. A client can have many orders (1:N), but orders have different types, described by the field TypeID. Now, I want to select the clients that have orders of a nu...
This is query upon the assumption that TypeId can be either 1 or 2. This will return ClientId that have both a Type1 and Type2 no matter how many of them. ``` Select ClientId, COUNT(distinct TypeId) as cnt from tblOrders o group by ClientId Having COUNT(distinct TypeId) >= 2 ``` `COUNT(distinct TypeId)` is how this r...
Here's one solution: ``` select * from clients c where exists (select 1 from orders o where typeid = 1 and o.clientid = c.clientid) and exists (select 1 from orders o where typeid = 2 and o.clientid = c.clientid) and exists (select 1 from orders o where typeid = 3 and o.clientid = c.clientid) -- additional t...
Find rows in a table based on the existance of two different rows in a 1:N-related table
[ "", "sql", "sql-server", "" ]
I am using SQL Server. I need to create a stored procedure that will update the Data field (table bellow) with different value for every ID value. (the values in the Data fields depend on the user input). ``` ID | Data --------- 1 | NULL 2 | NULL 3 | NULL ``` For example: if ID = 1, Data should be "Tes...
You need to use XML for sending data for multiple rows. For your current problem prepare (generate dynamically) an xml like below. ``` '<NewDataSet><Table><Id>1</Id><Data>test1</Data></Table><Table><Id>2</Id><Data>test2</Data></Table></NewDataSet>' ``` Then Prepare a procedure like below. ``` CREATE PROC [dbo].[Upd...
You need user-defined table types for this: Try this: ``` -- test table create table yourtable(id int not null, data [varchar](256) NULL) GO -- test type CREATE TYPE [dbo].[usertype] AS TABLE( [id] [int] not null, [Data] [varchar](256) NULL ) GO -- test procedure create procedure p_test ( @tbl dbo.[usertyp...
Stored Procedure that updates fields with different values
[ "", "sql", "sql-server", "stored-procedures", "sql-update", "" ]
I got a Strange issue in Mule .. I have a webservice exposed in Mule that perform simple CRUD operation.. Now the issue is there is a SQL query :- `if not exists (select * from sysobjects where name='getData' and xtype='U')create table getData (ID int NOT NULL, NAME varchar(50) NULL,AGE int NULL,DESIGNATION varchar(50...
Mule doesn't recognize the `if not exists...` query and thus doesn't know what to do with it. To fix this you need to: * create your own `org.mule.transport.jdbc.sqlstrategy.SqlStatementStrategyFactory` by sub-classing [the default one](https://github.com/mulesoft/mule/blob/mule-3.x/transports/jdbc/src/main/java/org/...
So as per David's suggestion, ended up using `if not exists` query in a Java component and Groovy component in the Mule flow and is working for me
Mule JDBC endpoint causing exception while executing SQL query
[ "", "sql", "mule", "mule-studio", "mssql-jdbc", "" ]
What is the Oracle equivalent of NVL for number datatypes? This works since the datatype is VARCHAR: ``` select nvl(enrol.OUAC_APPLNO, 'blank') Invalid_OUAC_APPLNO ``` But this doesn't work since the datatype is NUMBER: ``` select nvl(enrol.ouac_type_id, 'blank') REGTYP ```
There is no equivalent and no Oracle functions will accept this ([apart from `DECODE()` but don't do that](https://stackoverflow.com/q/13712763/458741)); you're going to have to convert your number to a character: ``` select nvl(cast(enrol.OUAC_APPLNO as varchar2(10)), 'blank') ``` You may need to change the number o...
it wont work because oracle wants every row should be in the same type otherwise you cannot run functions on that column, you have cast ouac\_type\_id to be varchar as below; ``` select nvl(cast(enrol.OUAC_APPLNO as varchar2(10)), 'blank') REGTYP ```
Oracle equivalent of NVL for number datatype
[ "", "sql", "oracle", "" ]
I have a test suite that runs against a database in a SQL Server 2012 cluster. I want this test suite to run as fast as possible. I'm willing to **sacrifice every durability and availability guarantee** for performance. The database is recreated during every test run, so it doesn't even have to survive server restarts....
If for some reason you are stuck on a clustered sql server instance but you do not want durability, maybe you could run your application on tempdb. Tempdb can be placed on local storage to avoid cluster overhead. Also note that data stored on tempdb will initially stay on the buffer pool, which is RAM memory, and only...
Could something like this work ([doc](http://msdn.microsoft.com/en-us/library/ms176061.aspx))? ``` CREATE DATABASE Sales ON ( NAME = Sales_dat, FILENAME = 'R:\saledat.mdf', SIZE = 10, MAXSIZE = 50, FILEGROWTH = 5 ) ``` Where `R:` is a [RAM Drive](https://serverfault.com/questions/208560/how-to-create...
How to create the fastest possible database on a SQL Server 2012 cluster, sacrificing any durability
[ "", "sql", "sql-server", "performance", "testing", "durability", "" ]
I'm trying to write a query that updates tbl8\_update\_transactions HID field (where it's null) with the primary key value (HID) that's highest in HOLIDAY\_DATE\_TABLE. I get the following error > "An aggregate may not appear in the set list of an UPDATE statement" I've read that I need to accomplish this using a sub...
You can write the query like this: ``` UPDATE tbl8_update_transactions SET HID = h.maxHID FROM (select max(HOLIDAY_DATE_TABLE.HID) as maxHID from HOLIDAY_DATE_TABLE) h WHERE tbl8_update_transactions.HID IS NULL; ``` I find it confusing to use a `from` clause and not have the main table mentioned there. I ...
I guess, your proposed code is correct, just missed SELECT ``` UPDATE tbl8_update_transactions SET HID = (SELECT h.maxHID FROM (select max(HOLIDAY_DATE_TABLE.HID) as maxHID from HOLIDAY_DATE_TABLE) h WHERE tbl8_update_transactions.HID IS NULL); ```
SQL Update Query - An aggregate may not appear in the set list of an UPDATE statement
[ "", "sql", "sql-server", "" ]
I have a database with auto-increment index. When I inserting a new item in the table, I don't know the index number. Is there a way to return new index of my item simultaneously? I could assume that the new index would be = `max-index + 1`. Is there some standard way to solve this? Thanks for help.
For MySQL, you use the [`LAST_INSERT_ID()`](http://dev.mysql.com/doc/refman/5.6/en/information-functions.html#function_last-insert-id) function, like this: ``` INSERT INTO tbl (auto,text) VALUES(NULL,'text'); SELECT LAST_INSERT_ID(); ```
In MSSQL use `@@IDENTITY`. For example `INSERT INTO [TaTAble] (testchamps) VALUES (tesvaleurs); SELECT @@IDENTITY as [index];`
SQL: Insert into table and return new index?
[ "", "sql", "indexing", "" ]
In SQL, how would I do something like a reverse join? For example suppose I have the following two tables ``` UsedSlide SlideId UserId SomeOtherValue LegacySlide SlideId UserId ``` How would I select all rows in `UsedSlide` where the `SlideId` and `UserId` don't match the values in any row of `Leg...
You could use the `not exists` operator: ``` SELECT * FROM UsedSlide u WHERE NOT EXISTS (SELECT * FROM LegacySlide l WHERE u.SlideId = l.SlideId AND u.UserId = l.UserId) ```
LEFT JOIN CAN BE USED ``` SELECT * from UsedSlide US LEFT JOIN LegacySlide LS ON US.SlideId = LS.SlideId and US.UserId = LS.UserId WHERE LS.SlideId is NULL AND LS.UserId is NULL ```
Get rows that don't match rows in another table
[ "", "sql", "" ]
I need to get the difference of the sums of two fields which are in single table (really sorry if this is confusing), please read on for an example ``` Id type account_id stock_id volume price value ========================================================== 1 BUY 1 1 5 500 ...
**Fiddle Test:** <http://sqlfiddle.com/#!2/53035/1/0> ``` select account_id, stock_id, sum(case when type = 'BUY' then volume else -volume end) as volume, sum(case when type = 'BUY' then value else -value end) as totalamount from tbl group by account_id, stock_id having sum(...
Just to reduce duplication I would change Brian's code to this: ``` SELECT account_id, stock_id, SUM(volume * type_sign) as total_volume, SUM(value * type_sign) as total_value FROM (select t.*, case when type = 'BUY' then 1 else -1 end as type_sign from tbl) t GROUP BY account_id, ...
SQL Query - How to get difference of sum of multiple of cells of rows
[ "", "mysql", "sql", "" ]
I have a PostgreSQL table with `id` field (`bigint`). Can I somehow (possibly with ORM) perform check that `id` value ends with '`00000`' (e. g. "7500000", "7600000", but not "123456")? Thanks for any help.
Django has an [`__endswith` clause](https://docs.djangoproject.com/en/1.7/ref/models/querysets/#std:fieldlookup-endswith) you could use. ``` qs = MyModel.objects.filter(myfield__endswith='00000') #id in your case ``` This fetches the queryset with all ids that end with `00000` Now, if you have an objects' instance a...
Try this: `YourModel.objects.filter(id__endswith='00000')`. It should also works on int fields :)
Django SQL LIKE on integer values?
[ "", "sql", "django", "" ]
I have a `survey` where users can post `answers` and since the answers are being saved in the db as a `foreign key` for each question, I'd like to know which answer got the highest rating. So if the DB looks somewhat like this: ``` answer_id 1 1 2 ``` how can I find that the answer with an `id` of `1` was selected m...
You can do group by and then sort ``` Select answer_id, count(*) as maxsel From poll Group by answer_id Order by maxsel desc ```
you could try: ``` YourModel.group(:answer_id).count ``` for your example return something like: `{1 => 2, 2 => 1}`
How to order by largest amount of identical entries with Rails?
[ "", "sql", "ruby-on-rails", "" ]
I have two tables (tags and tag map): Tags: ``` id text 1 tag1 2 tag2 3 tag3 ``` Tag map: ``` tag_id question_id 1 1 1 2 1 3 1 4 2 5 3 6 ``` I would like to get results like in the table below: ``` id text count 1 tag1 4 2 tag2 1 3 tag3 1 ``` M...
Use below query: ``` SELECT t1.id, t1.text, count(t2.question_id) AS COUNT FROM Table1 t1 LEFT JOIN Table2 t2 ON (t1.id=t2.tag_id) GROUP BY t1.id; ``` [SQL Fiddle Demo](http://sqlfiddle.com/#!2/3547a/6)
You can achieve this by grouping the individual ID's of the map table, and then counting the number of rows in each group. Edit: oh, and offcourse you need to filter out the rows which don't belong in the cartesian product that the joining of 2 tables generates by including a where-clause. ``` SELECT t.id, t...
Mysql | Count tags
[ "", "mysql", "sql", "count", "tags", "" ]
Following SQL table definition is illustrated one of create table statement from my MYSQL database which is developed by a former developer of my company. ``` DROP TABLE IF EXISTS `classifieds`.`category_vehicles`; CREATE TABLE `classifieds`.`category_vehicles`( `adv_id_ref` BIGINT UNSIGNED NOT NULL, `category_id_ref`...
There is no difference. `NULL DEFAULT NULL` is the implicit default. [From the CREATE TABLE documentation:](http://dev.mysql.com/doc/refman/5.5/en/create-table.html#idm46972477071408) * If neither NULL nor NOT NULL is specified, the column is treated as though NULL had been specified [From the "Data Type Default Val...
``` price DOUBLE NULL; ``` `price` is a double and can be null and its default value is null. ``` price DOUBLE DEFAULT NULL; ``` `price` is a double and can be null and its default value is null. ``` price DOUBLE NULL DEFAULT NULL; ``` `price` is a double and can be null and its default value is null.
NULL vs DEFAULT NULL vs NULL DEFAULT NULL in MYSQL column creation?
[ "", "mysql", "sql", "" ]
Scenario: I have 2 query form 2 table, just want to view both query results as a single query result. Details: Table: loantrans ``` +-----+----------+---------+---------+---------+ | tid | date | account | purpose | out | +-----+----------+---------+---------+---------+ | 1 |2014-08-12| 975 | Loan |...
You can just join the two queries. Using `WITH` is not necessary, but it greatly enhances the readibility of your query for cases like this. ``` WITH q2 AS (SELECT MONTH(`fdrtrans`.`date`) as month, SUM(`fdrtrans`.`in`) AS fdr FROM fdrtrans WHERE (`fdrtrans`.`date` BETWEEN '2014-01-01' AND '20...
In SQL Union is used to combine the output of select query. ``` select * from loantrans uninon select * from fdrtrans ```
How to get result from 2 different table?
[ "", "mysql", "sql", "" ]
> I have following records ``` NAME BIRTHDATE A 19/09/1990 B 25/09/1992 C 26/09/1993 ``` and current date is 19/09/2014 I want to get the birthday record from current date to next seven days below is my query. ``` CREATE PROCEDURE [dbo].[Get_Birthday] as begin Declare @CurrentDate d...
You may try the following ``` CREATE PROCEDURE [dbo].[Get_Birthday] as beginDeclare @CurrentDate date ,@NxtDate date set @CurrentDate = DATEADD(year,-DATEDIFF(year,'19000101',GETDATE()),GETDATE()); set @NxtDate = DATEADD(day,7,@CurrentDate) print @CurrentDate print @NxtDate select DocId, DoctorName,DOA,Email from vw...
Try this ``` SELECT DocId ,DoctorName ,DOA ,Email FROM vw_DoctorDetail WHERE ( DATEPART(DAY, DOA) BETWEEN DATEPART(DAY, GETDATE() + 7) AND DATEPART(DAY, GETDATE()) ) AND DATEPART(MONTH, DOA) = DATEPART(MONTH, GETDATE()) ```
How to get record between two date and month not year?
[ "", "sql", "sql-server", "sql-server-2008", "sql-server-2012", "" ]
I have a table called VAT, and I need to generate the monthly VAT report. So below is what I do... ``` SELECT SUM(Amount) AS "January" WHERE current_time_stamp BETWEEN '2014-01-01' AND '2014-01-310' FROM VAT ``` Just like the above query, I have 12 queries for January, February, March etc. So, instead of...
You can use conditional sum with case statement,below query will give you one row with 12 columns as for each month's sum ``` SELECT SUM(case when current_time_stamp BETWEEN '2014-01-01' AND '2014-01-31' then Amount else 0 end) AS `January` , SUM(case when current_time_stamp BETWEEN '2014-02-01' AND '2014-02-29...
Use a `GROUP BY`, like this: ``` SELECT SUM(Amount), MONTH(current_time_stamp) AS `Month` FROM VAT WHERE current_time_stamp BETWEEN '2014-01-01' AND '2014-12-31' GROUP BY MONTH(current_time_stamp) ``` However, it could be slow in case you have a lot of records.
One `Select` query to generate 12 result sets
[ "", "mysql", "sql", "database", "select", "" ]
I have found the first transaction (min), but when I add the column 'Winners', I get a row for their first win and a row for their first loss. I need only the first row, including whether they won or lost. I have tried aggregating the winners column to no avail. I would prefer not to sub-query if possible. Thanks in ad...
``` select sorted.* from ( SELECT dbo.ADT.Time AS FirstShowWager, dbo.AD.Account, dbo.AD.FirstName, dbo.AD.LastName, dbo.ADW.Winners, ROW_NUMBER ( ) OVER (partition by dbo.AD.Account, dbo.AD.FirstName, ...
It sounds like you don't care about the value of winners column, by grouping on winners you'd get multiple rows, one for null and others for non-null values. If you don't care about the amount they've won but just simply if they've won or lost, you can do something like this, ``` SELECT MIN(dbo.ADT.Time) AS FirstShow...
How to find the min, where TSQL groups by
[ "", "sql", "sql-server", "t-sql", "group-by", "greatest-n-per-group", "" ]
In my example, I have a table containing info about different venues, with columns for `city`, `venue_name`, and `capacity`. I need to select the `city` and `venue_name` for the venue with the highest `capacity` within each `city`. So if I have data: ``` city | venue | capacity LA | venue1 | 10000 LA | venue2 | 2...
``` select t.city, t.venue from tbl t join (select city, max(capacity) as max_capacity from tbl group by city) v on t.city = v.city and t.capacity = v.max_capacity ```
One way to do this is with `not exists`: ``` select i.* from info i where not exists (select 1 from into i2 where i2.city = i.city and i2.capacity > i.capacity); ```
SQL: get A with max B for every distinct C
[ "", "mysql", "sql", "sqlite", "greatest-n-per-group", "" ]
I have a database table that is used to version in/out results based on the user "version". I need to combine where the Source and Target match, and where there is a Activate record that comes directly after a Deactivate record. What I have currently: ``` ID Source Target Activate Deactivate 361440 1760 ...
This will work for the data sample you provided: ``` SELECT v1.ID, v1.source, v1.target, v1.activate, COALESCE(v2.Deactivate, v1.Deactivate) as Deactivate FROM Versions v1 LEFT JOIN Versions v2 ON v1.source = v2.source and v1.target = v2. target and v1.Deactivate + 1 =...
A totally different approach might use Oracle [`CONNECT BY` hierarchical queries](http://docs.oracle.com/cd/B19306_01/server.102/b14200/queries003.htm). The idea here is to build a path from "consecutive" rows (according to activate/deactivate): ``` SELECT CONNECT_BY_ROOT A.id AS ROOTID, A.SOURCE, A.TARG...
SQLcombine continuous records
[ "", "mysql", "sql", "sql-server-2008", "plsql", "" ]
I have the date to check as shown below: Input Date: ``` 17-09-2014 ``` For which I am converting in my dynamic script: Attempt #1: ``` CAST((convert(date,@FDate, 105)) AS nvarchar(50)) ``` Error: > Error converting data type varchar to date. Attempt #2: ``` convert(date, @FDate, 105) ``` Error: > The dat...
Try ``` convert(Datetime, @FDate,105) ``` I tried following script and it worked well for SQL Server 2005 and SQL Server 2012: ``` Declare @FDate varchar(100); set @FDate='17-09-2014'; Select convert(Varchar(50), convert(Datetime, @FDate,105) ,105) ``` Verified your fiddle script, just had small change and it worke...
There seems to be some confusion with [Convert](http://msdn.microsoft.com/en-US/us-en/library/ms187928.aspx). Comparing your fiddels from the comments and your shown Attempts. Your fiddels are showing `DECLARE @Date DATE`; The first argument is the targettype (Attempt #1) since your @FDate is already of type DATE `conv...
Error converting data type varchar to date in SQL Server 2008 R2
[ "", "sql", "sql-server", "sql-server-2008", "sql-server-2008-r2", "" ]
Consider the following table structure: ![Table structure with 3 tables](https://i.stack.imgur.com/wL5b8.png) I'm creating a stored procedure which will delete data from `RelatedA` and `RelatedB`. Afterwards I want to delete everything from `MasterData` that no longer has a relation in **both** `RelatedA` and `Relate...
First let's look at the ones that don't work ``` DELETE FROM MasterData WHERE ID IN ( SELECT MD.ID FROM MasterData MD JOIN RelatedA RelA on RelA.MasterDataID = MD.ID JOIN RelatedB RelB on RelB.MasterDataID = MD.ID WHERE RelA.MasterDataID IS NULL AND RelB.MasterDataID IS NULL ) ``` The `W...
I would suggest using `NOT EXISTS` ``` select md.* from MasterData md where not exists ( select 1 from RelatedA A where md.id = A.MasterDataID) and not exists ( select 1 from RelatedB B where md.id = B.MasterDataID) ; ``` Use these together (as shown above) or separately to assess the data. If satisfied...
Delete from table with no related data - WHERE NOT IN and JOIN both failing
[ "", "sql", "sql-server", "join", "where-clause", "sql-delete", "" ]
``` id | sent_time | status | campaignId | ---+-------------------+--------+------------+ 1 |2013-12-26 00:00:00| sent | 12 | ---+-------------------+--------+------------+ 2 |2013-12-26 00:00:00| sent | 12 | ---+-------------------+--------+------------+ 3 |2013-12-26 00:00:00| ...
Try this: ``` SELECT DATE(sent_time) AS sent_date, COUNT(id) AS total_sent_status FROM sms_table WHERE status = 'sent' AND campaignID = 12 AND sent_time BETWEEN '2014-08-26 00:00:00' AND '2014-09-30 23:59:59' GROUP BY sent_date ``` A few notes: * You can just move status filter to WHERE clause to simplify ...
You can move the condition on `status='sent'` to the WHERE clause and add `COUNT(id)` to the SELECT as follows: ``` SELECT DATE(sent_time) AS date_sent_time, COUNT(id) AS total_sent_status FROM sms_table WHERE sent_time BETWEEN '2014-08-26 00:00:00' AND '2014-09-30 23:59:59' AND campaignId = 12 AND status = 'sent' GR...
mysql - sum field by date range and group by
[ "", "mysql", "sql", "" ]
I have a table named `infoone` with two columns `address` and `locationCITY`. I want to write a search query. If user searches for `Edmonton`, it should return all records that have city `Edmonton`. If user searches for `12 main street Edmonton`, then it should return all respective records. `12 main street` is the ...
Free form searching for addresses is very difficult. Let's look at your examples ``` Address locationCity 12 Main Street Edmonton 456 Thomas Ave St Martin ``` **Possible searchs** * Edmonton - If only 1 word, should we assume it is a city? If so, how would the user find St. Martin? * 12 Main Street Edmo...
I don't believe your where clause is doing what you've intended. Let's remove the outer string var and reformat for readability: ``` select PLACEID,LEFT(CONVERT(NVARCHAR(1000),description),500)+'...' as des1 ,LOCATIONCITY,ADDRESS,DateT,RENT from infoone where( ((address like '%"+txtSearch.Text+"%') or (address ...
sql search query with like operator
[ "", "sql", "sql-server-2008", "t-sql", "sql-server-2012", "sql-like", "" ]
I have a `BaseProducts` table. I want to update a row from another row of same table. This is what I have tried but not working means not updation, ``` UPDATE DP SET DP.[Description] = SP.[Description] ................................ ................................ ................................ ,...
From what I understand you didn't mean to use an `inner join`, but a `cross join`: ``` UPDATE DP SET DP.[Description] = SP.[Description] ................................ ................................ ................................ ,[LastModificationDateUtc] = GETUTCDATE() FROM [dbo].[Base...
There is no need of inner join. This will work. ``` UPDATE DP SET DP.[Description] = SP.[Description] FROM [dbo].[BaseProducts] DP ,[dbo].[BaseProducts] SP WHERE SP.Id = @SourceBaseProductId AND DP.I...
Update a Row from another row of same table?
[ "", "sql", "sql-server", "" ]
I cant get this sql query work the way i want to. I am trying to match a record using "like" and "and" but i dont get any result. When i change it to "or" I get the result. Why do i not get any results when i use and? ``` SELECT a.MOD_REQ_NUM, a.REFERENCE_CODE, a.REFERENCE_VALUE, a.ACTIVE...
From your question and your comment to jmcilhinney's answer the SQL statement you want is: ``` SELECT a.MOD_REQ_NUM, a.REFERENCE_CODE, a.REFERENCE_VALUE, a.ACTIVE_DETAIL, b.REQUESTOR_WWID, b.REQUEST_DATE FROM DB_MOD_REQ_DETAILS a, DB_MOD_REQ_HEADER b WHERE a.MOD_REQ_NUM=b...
This part doesn't make sense: ``` and (a.REFERENCE_VALUE like '%43598%' and a.REFERENCE_CODE = 2) and (a.REFERENCE_VALUE like '%3694894%' and a.REFERENCE_CODE = 4) ``` How can `REFERENCE_CODE` ever be 2 and 4? At the very least, there should be an OR between those last two sets of conditions, i.e. ``` and ...
How to use multiple "like" and "and"
[ "", "sql", "sql-server", "" ]
I have two columns in the database: ``` Value | Date --------------------- 1.3 | 1410374280000 ``` Value is a float and Date is an epoch integer in milliseconds I am trying to optimize this query as this returns a few thousand rows. ``` SELECT * FROM data WHERE date >= [some_time_in_the_past] ``` Since I am rend...
To pick an arbitrary price with [`DISTINCT ON`](https://stackoverflow.com/questions/3800551/select-first-row-in-each-group-by-group/7630564#7630564) for each set of identical `truncated` (which fits your non-existing definition): ``` SELECT DISTINCT ON (1) (date / 5000) * 5000 AS truncated, price FROM data WH...
[`distinct on`](http://www.postgresql.org/docs/current/static/sql-select.html#SQL-DISTINCT) ``` select distinct on (truncated) * from ( select data.date / 5000 * 5000 as truncated, data.price from data where date >= [some_time_in_the_past] ) s order by truncated, price desc ``` If you want the lowest pric...
How to select distinct on one column while returning other columns
[ "", "sql", "postgresql", "distinct", "" ]
Good Day I am trying to remove a part of a string after a specific Character. It almost works when I use the specific Query: ``` LEFT(T1.ItemCode, CHARINDEX('-VASA', T1.ItemCode) - 1) AS 'Item Code ``` The problem I Have is that when I add the -1 at the end I get an error: Invalid length parameter passed on the LEFT...
Try this: ``` LEFT(T1.ItemCode, CHARINDEX('-VASA', T1.ItemCode + '-VASA') - 1) AS 'Item Code' ```
The problem is due to few of your item code which may not have the word '-VASA' and you are searching its position and again doing -1 which is negative. so first check weather your word is having '-VASA' in it or not. like : ``` Case when CHARINDEX('-VASA', T1.ItemCode) >=1 Then LEFT(T1.ItemCode, CHARINDEX('-VASA', T1...
Removing part of string after specific character
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have below tables: ``` Create Table Country(CountryID int primary key, CountryName nvarchar(100) not null) Create Table DeviceType(DeviceTypeID int primary key, DeviceTypeName nvarchar(100) not null) Create Table UserStat ( LocalID int primary key identity(1,1), TimePeriod datetime not null, CountryID int not null, ...
``` Declare @region nvarchar(50)='BOTH' Declare @calendarYear int = 2014 SELECT YEAR(U.TimePeriod) AS [Year] ,MONTH(U.TimePeriod) AS [Month] ,SUM(CASE WHEN D.DeviceTypeName = 'Mobile' THEN U.UserCount ELSE NULL END) AS [MobileUsers] ,SUM(CASE WHEN D.DeviceTypeName = 'Desktop' THEN U.UserCou...
I think this gives you want you want: ``` DECLARE @region varchar(10); DECLARE @calendarYear int; SET @calendarYear = 2014 SET @region = 'USA' ;WITH Data AS ( SELECT U.*, C.CountryName, D.DeviceTypeName FROM dbo.UserStat AS U WITH (NOLOCK) INNER JOIN dbo.Country AS C WITH (NOLOCK) ON C.CountryID=U.CountryID INNER JO...
Column is invalid in the select list because it is not contained in an aggregate function or in Group By clause
[ "", "sql", "sql-server", "group-by", "" ]
I have a configuration table and a users table. users: ``` | id | name | |----|----------| | 0 | Bob | | 1 | Ted | | 2 | Sam | ``` config: ``` | user_id | name | value | |---------|----------|-------| | 0 | a | 11 | | 0 | b | 2 | | 0 | c | 54...
Try this: ``` SELECT us.name FROM USERS us WHERE EXISTS (SELECT name FROM CONFIG WHERE name='a' AND value>4 AND user_id=us.id) AND EXISTS (SELECT name FROM CONFIG WHERE name='b' AND value<5 AND user_id=us.id) ``` Alternatively, you can use two joins: ``` SELECT us.name FROM USERS us, CONFIG c1, CONFIG c2 WHERE us.i...
Using groups: ``` SELECT u.name FROM users u JOIN config c ON c.user_id = u.id GROUP BY u.name HAVING MAX(c.name = 'a' AND c.value > 4) AND MAX(c.name = 'b' AND c.value < 5) ``` Using joins: ``` SELECT u.name FROM users u JOIN config a ON a.user_id = u.id AND a.name = 'a' AND a....
How to select data given several rows match?
[ "", "mysql", "sql", "" ]
how to get "AND" of all the values of a boolean column in a single sql query. ![enter image description here](https://i.stack.imgur.com/mr1bb.png) for above the o/p should be false, if all were true then o/p: true, if all/atlease one value false , then o/p: false.
Try this ``` IF EXISTS (SELECT ActiveStatus From TableName where ActiveStatus = 0) SELECT 'False' ELSE SELECT 'True' AS OutputColumn ```
You can indirectly use `MIN` for AND, and `MAX` for OR.if you take into account that a `BIT` colum is either zero or one: * `MIN`: only if all the values are 1 (true) the result will be 1 (true), it works like `AND` * `MAX`: if there is at least a 1 (true) the result will be 1 (true), it works like `OR` If you try to...
how to get "AND" of all the values of a boolean column in a single sql
[ "", "sql", "sql-server", "" ]
I have 54567 rows in this jos\_clientes\_contratos table; When I execute the query: ``` SELECT * FROM `jos_clientes_contratos` INNER JOIN jos_users ON jos_clientes_contratos.cpf_cnpj_cliente = jos_users.username; ``` It will return me 54560 rows. This means that there are 7 rows which were not listed on the result...
``` SELECT * FROM `jos_clientes_contratos` LEFT JOIN jos_users ON jos_clientes_contratos.cpf_cnpj_cliente = jos_users.username WHERE jos_users.username is null ``` Read up on Joins: <http://blog.codinghorror.com/a-visual-explanation-of-sql-joins/> LEFT Join basically says... Return all records from the left table...
You can do an anti-join: ``` SELECT * FROM t1 LEFT JOIN t2 ON (t1.key = t2.key) WHERE t2.key IS NULL ```
Query on mysql with inner join
[ "", "mysql", "sql", "" ]
I am trying to create a trigger to act like an exception that will not let a unordered pair not be inserted or updated in a dataset twice. For example given the set {A,B} where A and B are both columns that are primary keys and {A,B} exists in the table, I do not want to allow the set {B,A} to exist because that relat...
A function based index will work: ``` create unique index unique_pair_ix on pairing (least(element_one,element_two),greatest(element_one,element_two)); ``` Btw: Using a row trigger to select from the same table will cause: ``` ORA-04091: table XXXX is mutating, trigger/function may not see it ``` if you attempt to ...
> For example given the set {A,B} where A and B are both columns that are primary keys and {A,B} exists in the table, I do not want to allow the set {B,A} to exist because that relationship is already defined with {A,B}. The most straightforward way of enforce uniqueness is to add an unique index. But a "simple" index...
Trigger for unique pair constraint
[ "", "sql", "database", "oracle", "triggers", "" ]
I have 2 tables like this, **Table1** ``` Id Locations -- --------- 1 India, Australia 2 US , UK ``` **Table2** ``` Table2Id Location -------- -------- 101 Italy 102 UK 103 Hungary 104 India ``` I need to inner join these 2 tables on the condition, If `Locati...
[SQLFiddle example](http://sqlfiddle.com/#!2/1a3e4) for MySQL 5.5 [SQLFiddle example](http://sqlfiddle.com/#!3/1a3e4/1) for SQL **Table and data** ``` create table table1 (id int, locations varchar(100)); insert into table1 values (1, 'India, Australia'), (2, 'US, UK'); create table table2 (table2id int, location v...
If you are using Mysql you could take a look at the following option: [INSTR](http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_instr) ``` select table2id, location, table1.id, locations from table2 inner join table1 on instr(locations,location) >= 1; ``` [SQL Fiddle Link](http://sqlfiddle.com/#!2...
Inner-join in sql with contains condition
[ "", "sql", "inner-join", "contains", "exacttarget", "" ]
I have a particular question which is about MySQL. Please have a look at the query and the result set below: ``` SELECT `SentTo`, `Read` FROM `Emails` as t ``` ``` hello@mydomain.com | 1 -------------------------------- hello@mydomain.com | 0 -------------------------------- hello@mydomain.com | 1 -----...
This should work using `GROUP BY`: ``` SELECT `SentTo`, COUNT(*) Total, SUM(`Read`=0) FROM Emails GROUP BY `SentTo` ``` * [SQL Fiddle Demo](http://sqlfiddle.com/#!2/cd3f3/2)
A 'Group by' clause can solve this problem as follows: ``` SELECT `SentTo`, COUNT(*) as totalSend, (totalSend - SUM(`Read`)) as totalUnread FROM `Emails` GROUP BY `SentTo` ```
MySQL SUM(), COUNT() and GROUP BY
[ "", "mysql", "sql", "" ]
Why doesn't my query able to return any rows and not go to *Else* in my conditional statement? ``` For i As Integer = 0 To dtoffenseinfo2.Rows.Count - 1 Dim dtoffenseinfo3 As New DataTable Dim adapter3 As New OleDbDataAdapter("SELECT SUM(Price) AS TPRICE FROM tblFuelTransactionLo...
You forgot ``` adapter3.Fill(dtoffenseinfo3) ``` That's what's missing. :)
Who says that your query can't return any rows? You're not actually executing it so how would you even know? What's the point of the data adapter if you don't call its `Fill` method?
What's missing / wrong with my SQL Query? (Doesn't return any row)
[ "", "sql", "vb.net", "ms-access-2010", "oledb", "" ]
I have a database with 169 tables I need this column in every table: ``` wid integer not null primary key ``` I tried this(Thanks <https://stackoverflow.com/users/27535/gbn> for the solution): ``` SELECT 'ALTER TABLE ' + T.name + ' ADD foo int NULL' FROM sys.tables AS T WHERE T.is_ms_shipped = 0 ``` But it ...
``` do $$ declare selectrow record; begin for selectrow in select 'ALTER TABLE '|| T.mytable || ' ADD COLUMN foo integer NULL' as script from ( select tablename as mytable from pg_tables where schemaname ='public' --your schema name here ) t loop execute selectrow.script; end ...
Try this (change 'public' to whatever schema you're doing this in) ``` DO $$ DECLARE row record; cmd text; BEGIN FOR row IN SELECT schemaname, tablename FROM pg_tables WHERE schemaname = 'public' LOOP cmd := format('ALTER TABLE %I.%I ADD COLUMN foo SERIAL PRIMARY KEY ', row.schemaname, row.tablen...
PostgreSQL: How to add a column in every table of a database?
[ "", "sql", "database", "postgresql", "" ]
I'm trying to insert new user if not exist in users table, I tried this query but receive error: ``` INSERT INTO USER (name,email) VALUES ('John','john@mmm.com') WHERE NOT EXISTS (SELECT id FROM USER WHERE email = 'john@mmm.com') ``` how to insert user if not exists ? error: ``` #1064 - You have an error in you...
Use `insert . . . select`: ``` INSERT INTO USER (name, email) SELECT 'John', 'john@mmm.com' WHERE NOT EXISTS (SELECT id FROM USER WHERE email = 'john@mmm.com'); ``` I would write this as: ``` INSERT INTO USER (name, email) SELECT name, email FROM (SELECT 'John' as name, 'john@mmm.com' as emai...
Use [`INSERT ... SELECT`](http://dev.mysql.com/doc/refman/5.0/en/insert-select.html) instead of `INSERT`. ``` INSERT INTO USER (name,email) SELECT 'John','john@mmm.com' WHERE NOT EXISTS (SELECT id FROM USER WHERE email = 'john@mmm.com') ``` You also might consider using the `ON DUPLICATE KEY UPDATE` syntax extens...
MySQL: insert where not exists
[ "", "mysql", "sql", "" ]
I have two tables Those are following **Table Name : stockIn** ``` +----+-------------+------------+------------+ | Id | date | Itemname | stockInqty | +====+=============+============+============+ | 1 | 12/12/2014 | testitem | 12 | | 2 | 14/12/2014 | testitem11 | 20 | +---...
``` select * from ( SELECT t1.date as sdate , t1.itemname , t1.stockInqty AS stockInqty , t2.stockInqty AS stockOutqty FROM tbl1 t1 LEFT JOIN tbl2 t2 ON t1.`date` = t2.`date` AND t1.itemname = t2.itemname UNION SELECT t2.date as sdate , t2.itemname , t1.stockInqt...
Try this with order by date ``` SELECT t1.`date` , t1.itemname , t1.stockInqty AS stockInqty , t2.stockInqty AS stockOutqty FROM tbl1 t1 LEFT JOIN tbl2 t2 ON t1.`date` = t2.`date` AND t1.itemname = t2.itemname UNION SELECT t2.`date` , ...
Order by date in sql
[ "", "mysql", "sql", "" ]
I have a journal type table where it has `Account`, `Credit_Debit` and `Amount` columns. I am trying a `select` where by the result should look like a row followed by its contra amount row. Amount column is Numeric/Decimal. Expected output: An amount followed by its equivalent opposite(plus or minus) amount ``` expec...
Ok, this has worked. Thanks for everyone's efforts. ``` select * from table where amount between 100 AND 1000 UNION select * from table where amount between -1000 AND -100 ```
Your second one will work with an OR operator. ``` select * from table where (amount between('100') AND ('1000')) OR (amount between('-100') AND ('-1000')) ``` But it will show rows containing amounts between -1000 and 1000 minus those with amounts between -100 and 100. To do what you want to do, if I get it right, ...
How to apply multiple between operator in SQL
[ "", "sql", "oracle", "" ]
I have the following table: ``` ID GroupID Date Value 1 A 2014-06-01 20 2 A 2014-06-02 21 3 A 2014-06-03 22 4 B 2014-06-01 50 5 B 2014-06-02 76 6 A 2014-06-04 25 7 C 2014-06-01 70 8 A 2014-06-05 29 ``` ...
you just set RowNumber Column Value to RowNumber%24+1 then when row number reached to 24 then start from 1 ``` SELECT (ROW_NUMBER() OVER (PARTITION BY GroupID ORDER BY ID) -1)%24+1 as RowNumber, * FROM Table ``` because row number to start from 1 i minus row number -1 to s...
You can achieve this using **decode** function available in SQL. Once the RowNumber reaches 25, RowNumber starts again from 1. try executing below query: select ID,GroupID,Date,Value, decode(mod(rownum,24), 0 , 24, mod(rownum,24)) mod\_Val from Table
Adding limited Row number SQL
[ "", "sql", "sql-server", "sql-server-2008", "" ]
My question is very similar to this one: ## **[SE Question](https://stackoverflow.com/questions/92093/removing-leading-zeroes-from-a-field-in-a-sql-statement)** However I want to run a query on a table, and actually update the values in that table, not just Select them. Im not sure how to select a value and then Upd...
So adapt the query for an `update`: ``` update table t set ColumnName = substring(ColumnName, patindex('%[^0]%', ColumnName), 10); ```
If all the columns are numeric use this: ``` UPDATE table SET col = cast(cast(col as int) as varchar(10)) WHERE col like '0%' ``` If some values are not numeric ``` UPDATE table SET col = stuff(@a, 1, patindex('%[^0]%', @a) - 1, '') WHERE col like '0%' ```
Remove Leading Zeros in a column in a sql server table,
[ "", "sql", "sql-server", "" ]
I need one very expert help, I can't seem to find the answer to this, the problem is, find the titles and ISBNs of books that have the same title and publishers as at least 2 other books. Order it by title. So basically, everything is coming from the book table. ``` CREATE TABLE BOOK ( ISBN VARCHAR2(20), Titl...
This ought to do it: ``` select isbn, title from books where (title,publishername) in(select title,publishername from books group by title,publishername having count(*) >=3) order by title; ```
Step 1: Find combinations of title and publisher that have at least 2 books: ``` SELECT title, PublisherName FROM BOOK GROUP BY title, PublisherName HAVING COUNT(*) > 1 ``` Step 2: find all other books that have this title and publisher: ``` SELECT * FROM Books b1 WHERE EXISTS( SELECT title, PublisherName ...
How can we retrieve same data in one table?
[ "", "sql", "oracle", "" ]
I have 3 tables, A, B,C * Table A,Columns: latlong, name * Table B, columns : code, name * Table C, Columns : latlong, code I want to update table A,column Name with the values from Table B, Column Name, something like: ``` update A set A.name = (select b.name from B where code = c.code) where a.latlong = c.latl...
You have mentioned in your question the following: > I want to update table A,column Name with the values from Table B, Column Name But what I can see from your query is that actually , you need only those values of the column `Name` of table `B` which has same value of `code` as in table `C`, and that your `latlong`...
You can do this with an `update` using `join`: ``` update a set name = b.name from a join c on c.latlong = a.latlong join b on b.code = c.code; ```
Sql Subquery result
[ "", "sql", "sql-server", "" ]
I Have a table that has order data like this: Table Order\_Detail and Item\_Master are joined by Item# We want to report on order number, Order\_Detail table: ``` Order# Item# 1234 IPhone6 1234 IPhone5 1234 Battery join Item_Master: Item# Item_type Desc IPhone6 ...
this query will return ordernums where the only ordered item type is 'phone' ``` select ordernum from order_detail od join item_master im on im.itemnum = od.itemnum group by ordernum having count(case when im.item_type <> 'Phone' then 1 end) = 0 and count(*) = 1 ``` if you want to allow multiple 'phone' orders you ca...
Your question is a little confusing. Are you looking to get a count of order numbers where `Item_Type = 'Phone'`? If so the follwoing should work for you: ``` SELECT COUNT(DISTINCT OrderNum) AS OrderNumCount FROM Order_Detail o INNER JOIN Item_Master i ON o.ItemNum = o.ItemNum WHERE Item_type = 'Phone' ``` Or are you...
Count in Query 400 not passing correctly
[ "", "sql", "ibm-midrange", "db2-400", "" ]
I have users table ``` ID NAME 1 John 2 Mike 3 Jack ``` and table with attributes and user IDs ``` USER ATTRIBUTE 1 1 1 2 2 4 ``` I need to select all users with attribute 1 AND 2 (so, in this example user #1 John). Attributes can be more than two. I'v tried ``` SELECT * FROM u...
You will need to use a combination of `IN()` and `GROUP BY ... HAVING` to achieve this. Also no need for a join if all you need is user ID's. So something like: ``` SELECT user, COUNT(attribute) AS attribute_count FROM attributes WHERE attribute IN(...) /* include your set of attributes here */ GROUP BY user HAVING at...
having clause can be used with sum ``` SELECT u.id FROM user u INNER JOIN attributes a ON u.id = a.user group by u.id having ( sum(case when attribute in (1,2) then 1 else 0 end) ) =2 ```
Join and multiple and conditions
[ "", "mysql", "sql", "symfony1", "doctrine-1.2", "" ]
If Oracle fails to execute the below query due to whatever reason, will the *supplier\_seq* get incremented? When exactly does Oracle increment sequences? ``` INSERT INTO suppliers (supplier_id, supplier_name) VALUES (supplier_seq.NEXTVAL, 'Kraft Foods'); ```
The sequence is incremented as soon as `nextval` is called. This increment will never be rolled back. The value is "gone". The only situation where this value could ever be generated again by the sequence, is if the sequence is set to `CYCLE` and it wraps around. > *due to whatever reason* The reason *does* matter. ...
Independently from whether query fails or not, Oracle Sequences are synchronously incremented in all sessions, right when they are called. However, if there is a syntax error in your statement (wrong tablename, column name etc.), sequence will stay the same since the query won't be executed.
oracle sequence NEXTVAL behavior in case of query execution failure
[ "", "sql", "oracle", "sequence", "sql-execution-plan", "" ]
I am trying to find out if there is any way to aggregate a sales for each product. I realise I can achieve it either by using group-by clause or by writing a procedure. example: ``` Table name: Details Sales Product 10 a 20 a 4 b 12 b 3 b ...
You could do ``` SELECT product, (SELECT SUM(sales) FROM details x where x.product = a.product) sales from Details a; ``` (and wrap it into another select to simulate the `HAVING`).
It's possible to use analytic functions to do the sum calculation, and then wrap that with another query to do your filtering. [See and play with the example here.](https://data.stackexchange.com/stackoverflow/query/226781/sum-without-group-by) ``` select running_sum, OwnerUserId from ( select id, scor...
Is it possible to calculate the sum of each group in a table without using group by clause
[ "", "sql", "sql-server", "database", "t-sql", "plsql", "" ]
I have two tables, `CountLogs` and `RegisterCountLogs`. They both have the same FK constraints, so I'd like to transfer the Timestamp from one to the other. How can I achieve this in one SQL statement? E.g. ``` SELECT [DeviceSerial] ,[LogEntryID] ,[Timestamp] FROM [dbo].[CountLogs] UPDATE RegisterCount...
Use a join: ``` UPDATE RegisterCountLogs SET Timestamp = [OTHERQUERY?].Timestamp FROM RegisterCountLogs INNER JOIN [OTHERQUERY?] ON RegisterCountLogs.DeviceSerial = [OTHERQUERY?].[DeviceSerial] AND RegisterCountLogs.[LogEntryID] = [OTHERQUERY?].[LogEntryID] ```
try this... ``` UPDATE R SET R.Timestamp = C.Timestamp FROM RegisterCountLogs R INNER JOIN [dbo].[CountLogs] C ON (R.[DeviceSerial] = C.[DeviceSerial] AND R.[LogEntryID] = C.[LogEntryID]) ```
Update rows in one table, with data from another
[ "", "sql", "sql-server", "" ]
I am working on Averaging several rows of data and I have been busting my butt figuring it out and I "think" Im down to the last error. ``` ERROR 1584 (42000): Incorrect parameters in the call to stored function 'cast' ``` I get this when I run this ``` select avg(volume) from _AAPL WHERE date between cast('2014-02-...
You should not have any space after "CAST" : > cast('2014-05-05' as DATE) instead of ``` cast ('2014-05-05' as DATE) ``` By the way i'm not sure it's mandatory to cast dates when they are already formatted like 'yyyy-mm-dd' : i would just write ``` `column` BETWEEN '2014-02-03' AND '2014-05-05' ```
In [mysql](/questions/tagged/mysql "show questions tagged 'mysql'") you can convert a string literal to a date by using the [`str_to_date`](http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_str-to-date) function: ``` SELECT AVG(volume) FROM _AAPL WHERE `date` BETWEEN STR_TO_DATE ('2014-...
Average in mysql with date
[ "", "mysql", "sql", "" ]
I have this stored procedure: ``` exec SearchResume @KeywordSearch=N'', @GreaterThanDate='2013-09-22 00:00:00', @CityIDs=N'0,56,31,271,117,327,3,328,228', @ProvinceIDs=N'0,1,12,13', @CountryIDs=N'1', @IndustryIDs=N'0,2,3,4,38,113,114,115,116,117' ``` Which doesn't return any results because the ids are in nvarchar...
You can create a Table-Valued Function which takes the nVarChar and creates a new record for each value, where you tell it the delimiter. My example here returns a table with a single Value column, you can then use this as a sub query for your IN Selection : ``` Create FUNCTION [dbo].[fnSplitVariable] ( @List nva...
``` DECLARE @SQL AS NVARCHAR(MAX) SET @SQL = 'SELECT DISTINCT UserID, ResumeID, CASE a.Confidential WHEN 1 THEN ''Confidential'' ELSE LastName + '','' + FirstName END as ''Name'', a.Description ''ResumeTitle'', CurrentTitle, ModifiedDate, CASE ISNULL(b.SalaryRan...
cast list of strings as int list in sql query / stored procedure
[ "", "sql", "sql-server", "sql-server-2008", "stored-procedures", "sql-server-2008-r2", "" ]
**How do I create a new sequence taking its name is from a variable?** Let's take a look at the following example: ``` CREATE OR REPLACE FUNCTION get_value(_name_part character varying) RETURNS INTEGER AS $BODY$ DECLARE result bigint; sequencename character varying(50); BEGIN sequencename = CONCAT('cons...
The currently accepted answer has a number of problems. Most importantly it fails to take the **schema** into account. Use instead: ``` CREATE OR REPLACE FUNCTION get_value(_name_part text) RETURNS bigint AS $func$ DECLARE _seq text := 'constant_part_of_name_' || _name_part; BEGIN CASE (SELECT c.relkind = 'S':...
Try this. Hope this work for you. ``` CREATE OR REPLACE FUNCTION get_value(_name_part character varying) RETURNS INTEGER AS $BODY$ DECLARE result bigint; sequencename character varying(50); v_sql character varying; BEGIN sequencename = CONCAT('constant_part_of_name_', _name_part); IF((SELECT CAST(C...
Sequence name taken from variable
[ "", "sql", "postgresql", "sequence", "plpgsql", "dynamic-sql", "" ]
I have been working at this for hours and I cannot figure out what is wrong... I have written this code ``` INSERT INTO Agents (ID,Name,Phone,Cert_Level,Join_Date) VALUES (1,’Chris’,’317-9578’,1,’01-NOV-91’); ``` and I get the same missing comma error over and over and I cannot find the problem PLEASE HELP ME here ...
try the below code as you are different quotes, replace ’ to ' . ``` INSERT INTO Agents (ID,Name,Phone,Cert_Level,Join_Date) VALUES (1,'Chris','317-9578',1,'01-NOV-91'); ``` Cheers !!
Your string literals are delimited with unicode character Right single quotation mark (u+2019) instead of Apostrophe (' u+0027). You can try typing the apostrophes. ``` ’Chris’ ``` vs ``` 'Chris' ```
Oracle Missing Comma
[ "", "sql", "database", "oracle", "" ]
Supose we've got the following dataset: ``` DATE VAR1 VAR2 1 A 1 2 A 1 3 B 1 4 C 2 5 D 3 6 E 4 7 F 5 8 B 6 9 B 7 10 D 1 ``` Each record belongs to a person, the problem is that a single person can have more than one record with different...
I forgot to post my final solution, it is a SAS macro. I've made another one for 3 variables. ``` %MACRO GROUPER2(INDATA,OUTDATA,ID1,ID2,IDOUT,IDN=_N_,MAXN=5); %PUT ****************************************************************; %PUT ****************************************************************; %PUT ...
``` %macro grouper( inData /*Input dataset*/, outData /*output dataset*/, id1 /*First identification variable (must be numeric)*/, id2 /*Second identification variable*/, idOut /*Name of variable to contain group ID*/, maxN = 5 /*Max number of itterations in case of failure*/); /* Assig...
How to group using two variables
[ "", "sql", "sas", "" ]
Assume I have a database set up and a table named `MyTable` which contains a large number of records (tens of thousands). Assume a query as follows... ``` select * from MyTable where ColumnX = 'X' ``` ... returns just a handful of records (< 10). Let's say I wanted to filter this result set further to only those reco...
SQLite's documentation describes [multiple optimizations](http://www.sqlite.org/optoverview.html#or_opt) that can be done on queries with OR, and says: > For any given query, the fact that the OR-clause optimization described here can be used does not guarantee that it will be used. SQLite uses a cost-based query plan...
You can try with IN clause : ``` select * from MyTable where ColumnX = 'X' and ColumnY in ('Y1','Y2') ```
Is it better to avoid OR clauses in database queries?
[ "", "android", "sql", "sqlite", "android-sqlite", "database-performance", "" ]
I have the following query ``` SELECT COUNT( iContactId ) AS Users, DATE( dCreatedAt ) AS ActivityDate FROM contacts WHERE iAppId =".$iAppId." AND DATE(dCreatedAt) IN (CURRENT_DATE(), CURRENT_DATE()-1 ) GROUP BY ActivityDate ``` by this i am getting ``` Users |ActivityDate 1 |2014-09-19 ``` i want 0 if there...
You could use union ``` SELECT COUNT( iContactId ) AS Users, CURRENT_DATE() AS ActivityDate FROM contacts WHERE iAppId =".$iAppId." AND DATE(dCreatedAt) = CURRENT_DATE() UNION SELECT COUNT( iContactId ) AS Users, CURRENT_DATE() - 1 AS ActivityDate FROM contacts WHERE iAppId =".$iAppId." AND DATE(dCreatedAt) = CURRE...
## **QUERY** ``` SELECT COUNT(C.iContactId) AS Users, DATE(C.dCreatedAt) AS ActivityDate FROM contacts C LEFT OUTER JOIN ( SELECT CURRENT_DATE() AS Dates FROM dual UNION SELECT CURRENT_DATE() - 1 AS Dates FROM dual ) D ON D.Dates = DATE(C.dCreatedAt) WHERE C.iAppId =".$iAppId." GROUP B...
Get the 0 value if No result in column -- MySQL
[ "", "mysql", "sql", "select", "" ]
``` SELECT * FROM TableName WHERE ORDER BY CASE @OrderByColumn WHEN 1 THEN Forename WHEN 2 THEN Surname END; ``` I have a statement like above which lets me dynamically choose how to order the results of a query. However, how do I specify that I want the Forename ordered `DESC` and the Surname `AS...
You need to split your `ORDER BY` in two parts: ``` SELECT * FROM TableName WHERE ORDER BY (CASE @OrderByColumn WHEN 1 THEN Forename END) DESC -- Forename --> descending , (CASE @OrderByColumn WHEN 2 THEN Surname END) ASC -- Surname --> ascending ```
You need two clauses in the `order by`: ``` ORDER BY (CASE WHEN @OrderByColumn = 1 and @Dir = 'ASC' THEN Forename WHEN @OrderByColumn = 2 and @Dir = 'ASC' THEN Surname END) ASC, (CASE WHEN @OrderByColumn = 1 and @Dir = 'DESC' THEN Forename WHEN @OrderByColumn = 2 and @D...
Case statement for Order By clause with Desc/Asc sort
[ "", "sql", "sql-server", "t-sql", "" ]
I have a SQL Server stored procedure that looks simplified like this: ``` begin select ( case when @Method = 'phone' then u.PhoneNumber when @Method = 'email' then u.Email end ) from Table a join Users u on a.ID = u.Id where a.Active = 1 and -- This part does not work case ...
Change your where condition as below ``` where a.Active = 1 and ( (@Method = 'phone' and u.PhoneNumber is not null) or (@Method = 'email' and u.Email is not null) ) ```
you not need to use case when in where you can use ``` where a.Active = 1 and -- This part now work ( (@Method = 'phone' and u.PhoneNumber is not null) OR (@Method = 'email' and u.Email is not null) ) ```
SQL Server Procedure Case when I where clause
[ "", "sql", "sql-server", "t-sql", "" ]
I am trying to product a sales report that shows for example ``` itemid salesdate qty_sold item1 1/9/14 3 item1 1/9/14 2 item1 1/9/14 5 item2 2/9/14 2 item3 4/9/14 1 ``` The problem I have is because the sale...
For the SQL you have included in your question you would need to use the aggregate function SUM with the GROUP BY statement. ``` SELECT st.orderdate, sl.itemid, SUM(sl.qty) FROM salestable st INNER JOIN salesline sl ON salestable.salesid = salesline.salesid GROUP BY st.orderdate, sl.itemid ``` You...
If I understand it correctly, your problem is with sorting the record. If that is the case, then append this to your SQL code. ``` ORDER BY salesdate DESC ```
SQL Query to use in report builder 3.0: grouping results together
[ "", "sql", "" ]
I have a database called Clients\_Visits and I have found that there are so many duplicate records of a patricular patient based on their visit date and type of visit. I'm just wondering if somebody can help me eliminate/drop this records which are occupying spaces. Sample Data: **Clients\_Visits:tbl** ``` RecID | C...
This Statement deletes all the records with identic Customer\_No, DateOfVisit and VisitType. The record with the lowest RecID stays in DB ``` DELETE FROM Clients_Visits v1 WHERE EXISTS (SELECT RecID FROM Clients_Visits v2 WHERE v1.Customer_No=v2.Customer_No AND v1.DateOf...
Assuming you want to keep the highest `recid`, there are several ways to do this. One is to establish a `row_number` and delete accordingly: ``` with cte as ( select *, row_number() over (partition by customer_no, dateofvisit order by recid desc) rn from yourtable ) delete f...
SQL - Drop exactly duplicate rows of records based on 2 columns as validation
[ "", "sql", "sql-server", "database", "t-sql", "" ]
I am creating a package that will run every fifteen minutes and write a csv file into a shared folder. I am stuck on the query. I need the query to only go back to 12:00AM of the same day. Once it's the next day I need to have the query run only for that same day and not go back to the previous day. I have tried this ...
If you are using SQL Server 2008 + you can simply use: ``` SELECT CAST(GETDATE() AS DATE) ``` To get the current date.
You can use the following to get the current date (I'm sure there are many other methods as well) ``` SELECT CONVERT(DATETIME, CONVERT(VARCHAR(10)DATE, GETDATE(), 101)) ``` as the -1 comment pointed out using varchars with dates is a bad idea (though everyone seems to do it all the time. Another solution would be: `...
How to run same day query for SQL Server
[ "", "sql", "datetime", "sql-server-2008-r2", "" ]
Firstly I'm a sql rookie and only know the basics. I have tried googling ( and have seen some references and example of similar but I was not able to follow or apply to my problem), I'm not even 100% if it is possible in my situation. I'm trying figure out how to perform a select that involves calculating a column base...
You can calculate the carry using variables ``` select `Date`, max(case when rowNum = 1 then carry end) carry, sum(case when type = 'payin' then amount else 0 end) total_in, sum(case when type = 'payout' then amount else 0 end) total_out, sum(amount) balance from ( select `Date`, time, @balance carry, ...
I believe you can get your first result with the following: ``` SELECT date, time, @carry := COALESCE(@carry,0) carry, amount, @carry := @carry + amount balance, type FROM transaction ORDER BY date, time ``` [**SQL FIDDLE DEMO**](http://sqlfiddle.com/#!2/12db1/5)
How Can I reference pervious row in a mysql select query
[ "", "mysql", "sql", "mamp", "" ]
Using Django, I often have to add new fields to our PostgreSQL database. The fields usually have an initial value and they must be set to NOT NULL. My procedure for this involves three steps: 1) Add field and set initial value: ``` ALTER TABLE my_table ADD COLUMN my_field boolean; UPDATE my_table SET my_field = FALSE...
Did you try this; ``` alter table my_table add column my_field1 boolean default false NOT NULL, add column my_field2 boolean default false NOT NULL; ```
You should do that by two steps: 1. Add column 2. Alter column: set constraint, add default Query: ``` ALTER TABLE my_table ADD COLUMN my_field boolean; ALTER TABLE my_table ALTER COLUMN my_field SET NOT NULL, ALTER COLUMN my_field TYPE boolean USING false; ``` Or this: ``` ALTER TABLE my_tabl...
Add a new column to PostgreSQL database, set initial value and set NOT NULL all in one go
[ "", "sql", "postgresql", "ddl", "alter-table", "" ]