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 problem with my MySQL query with large data access, When the query optimized with join it gives the output within 122 seconds for the data of one week. Then for one month data it takes 526 seconds for the process. I want to optimize this query for less amount of process time per year or if there any way to opt...
This is your query: ``` SELECT COUNT(t.id) AS m_count, t.date, t.timeslot_id, t.tv_channel_id, t.district, t.area FROM `mdiaries` m INNER JOIN `tv_diaries` t ON m.member_id = t.member_id WHERE m.date >= '2014-01-01' AND m.date <= '2014-01-07' AND t.date >= '2014-01-01' AND t.date <= '2014-01-07'...
Try adding multiple-columns index on all columns referenced in `GROUP BY` clause, as mentioned [in the documentation](http://dev.mysql.com/doc/refman/5.0/en/group-by-optimization.html). ``` INDEX grp (date, timeslot_id, tv_channel_id, district, area) ```
MySQL Query Optimization for JOIN Large Tables
[ "", "mysql", "sql", "innodb", "" ]
I have table With ID,Sub\_ID and value coloumns ``` ID SUB_ID Value 100 1 100 100 2 150 101 1 100 101 2 150 101 3 200 102 1 100 ``` SUB ID can vary from 1..maxvalue( In this example it is 3). I need Sum of values for each Sub\_ID. If SUB\_ID is less than MAXVALUE for a particlaur ID then it should take ...
[SQL Fiddle](http://sqlfiddle.com/#!4/af87b/3) **Oracle 11g R2 Schema Setup**: ``` CREATE TABLE TableA ( ID, SUB_ID, Value ) AS SELECT 100, 1, 100 FROM DUAL UNION ALL SELECT 100, 2, 150 FROM DUAL UNION ALL SELECT 101, 1, 100 FROM DUAL UNION ALL SELECT 101, 2, 150 FROM DUAL UNION ALL SELECT 101, 3, 200 FROM ...
Try this ``` SELECT SUB_ID,SUM(values), (SELECT DISTINCT SUBSTRING( ( SELECT '+'+ CAST(values AS VARCHAR) FROM table_Name AS T2 WHERE T2.SUB_ID = d.SUB_ID FOR XML PATH ('') ),2,100000)[values]) as values FROm table_Name d GROUP BY SUB_ID ```
Oracle sql group sum
[ "", "sql", "oracle", "oracle11g", "" ]
I am running a SQL query where I am trying to get both the DOB and Age field as blank (' ') as opposed to `NULL`. I have managed to use the `ISNULL` function to change the DOB from `1900-01-01` to ' '. Originally my DOB was ``` SELECT isnull(DOB,'') DOB ``` which was bring back `1900-01-01` instead of `NULL` With t...
This is your age: ``` DATEDIFF(hour,dob,GETDATE())/8766 ``` It is a number. To make it a string, do this: ``` cast(DATEDIFF(hour,dob,GETDATE())/8766 as varchar (15)) ``` Then you can use isnull because your datatypes are the same ``` isnull(cast(DATEDIFF(hour,dob,GETDATE())/8766 as varchar (15)), '') ```
You could use a simple CASE statement. ``` case when dob = '' then '' else datediff(hour, dob, getdate())/8766 end as [Age] ``` There's probably a more elegant way to do it though.
<SQL Server>DOB and Age field as blank using SQL
[ "", "sql", "sql-server", "" ]
I have a table which has a int column representing for scores of student. I want to select the 2nd highest score if there does exists for 2nd highest score, and if not, return null. Wondering how to implement in SQL. I am using MySQL/SQL Workbench.
This query would return the second highest value if present or-else NULL ``` SELECT MAX(score) FROM table_name WHERE score<>( SELECT MAX(score) FROM table_name); ```
Please try executing following sql query for retrieving 2nd highest score ``` SELECT score from table order by score desc limit 1,1 ``` The above query will return 2nd highest score if it exists or **NULL** if it the record does not exists
how to check if there exists 2nd highest score in SQL?
[ "", "mysql", "sql", "" ]
I'd like to perform a SQL SELECT query which will go across two tables. I understand I'll need to use a join, but I'm not entirely sure how this would work (apologies - quite new to SQL). ``` SELECT COUNT(RSO_ParentID) AS 'Calls in Queue' FROM Task, Incident WHERE Task.OwnerTeam = '2nd Line Support' AND (Task.Stat...
There are so many different ways to solve a problem with SQL and a number of ways to filter out and reduce your dataset to what you want to see. Lets look at your original SQL Statement: ``` SELECT COUNT(RSO_ParentID) AS 'Calls in Queue' FROM Task, Incident WHERE Task.OwnerTeam = '2nd Line Support' AND (Task.Statu...
``` SELECT COUNT(RSO_ParentID) AS 'Calls in Queue' FROM Task JOIN Incident ON --task.somecolumn = incident.somecolumn WHERE Task.OwnerTeam='2nd Line Support' AND (Task.Status='Accepted' OR Task.Status='Waiting') AND Incident.Status='Waiting' ``` You don't have a `join` condition in your query, which means it would g...
SQL Select Query - Two Tables
[ "", "sql", "" ]
I've encountered a bit of a mental roadblock regarding the way a specific integer field is storing data. Specifically, there is a column with integers that range from 1 - 127; each integer represents a combination of different days of the week. For example: Monday = 2^0 or 1, Tuesday = 2^2 or 2, Wednesday = 2^3 or 8; ...
What you're dealing with is referred to as bitwise operators. Here's a [good read](https://www.mssqltips.com/sqlservertip/1218/sql-server-bitwise-operators-store-multiple-values-in-one-column/) on it with clear simple examples. For the sake of completeness, here is what you're looking at broken down into columns for ...
It seems like you could just grab the bit you need and store the result in their own field for each day of the week. ``` SELECT cast(day_of_week & 1 as bit) AS 'Monday', cast(day_of_week & 2 as bit) AS 'Tuesday', cast(day_of_week & 4 as bit) AS 'Wednesday', cast(day_of_week & 8 as bit) AS 'Thursday', ...
Multiple days of week stored in one field
[ "", "sql", "sql-server-2008", "date", "" ]
I have table with a list of dates. These are not ordered in the database, but using a SQL SELECT query. There are two intervals I want to calculate. The first is not a problem, which is calculating the interval between the dates in the same row. ``` Date 1 Date 2 (Interval 1) 1950-01-01 1960-01-01 (10.00)...
Like @Mihai mentioned, you would need to use a `row_number` field and do a left join to get the previous date values: ``` SET @row_number:= 0; SET @row_number1:= 0; select q1.* ,q2.Date2 as PreviousDate from (SELECT @row_number:= @row_number + 1 AS row_number ,dt.* FROM datetable dt ) q1 left join (SELE...
What you need to do is add a row number column in your query, then left join it with itself on firstinstance.rownumber = secondinstance.rownumber + 1 Then you can do the calculus you need. Hope this helps!
Copying and shifting column in SQL query
[ "", "mysql", "sql", "" ]
I have added a suffix id to allow merging of data in sql using the following query ``` Update [databasename].[dbo].[customers] set [relnum] = RTRIM(relnum) + '-9999' GO ``` It has been run more than once. I need to know how to remove it completely and also how to only leave one instance of -9999 on the field in the d...
This covers all possible scenarios. Using `CHARINDEX()` and `LEFT()` functions: [Fiddle sampl](http://sqlfiddle.com/#!3/81e5d/1)e ``` UPDATE Customers SET relnum = CASE WHEN CHARINDEX('-9999', relnum, 1) > 0 THEN LEFT(relnum, CHARINDEX('-9999', relnum, 1)-1) ELSE relnum ...
Maybe: ``` Update [databasename].[dbo].[customers] set [relnum] = replace(relnum,'-9999-9999','-9999') ``` Run it a few times and you'll be fine. Hope it helps!
How to remove suffix id added on sql server that was previously added SQL
[ "", "sql", "sql-server", "" ]
I have data as per the table below, I pass in a list of numbers and need the `raceId` where all the numbers appear in the the data column for that race. ``` +-----+--------+------+ | Id | raceId | data | +-----+--------+------+ | 14 | 1 | 1 | | 12 | 1 | 2 | | 13 | 1 | 3 | | 16 | 1 | ...
``` select raceId from yourtable where data in (1,2,7) group by raceId having count(raceId) = 3 /* length(1,2,7) */ ``` This is assuming raceId, data pair is unique. If it's not the you should use ``` select raceId from (select distinct raceId, data from yourtable where data in(1,2,7)) group by raceId hav...
This is an example of a "set-within-sets" query. I like to solve these with `group by` and `having`. ``` select raceid from races where data in (1, 2, 7) group by raceid having count(*) = 3; ```
SQL Select and Group By clause
[ "", "sql", "sql-server", "" ]
I have a set of duplicate records in a SQL db like so: ``` Id | Prop1 | Prop2 -------------------------- 1 | aaa | aaa 2 | aaa | aaa 3 | bbb | bbb 4 | bbb | bbb 5 | ccc | ccc 6 | ccc | ccc ``` I need to select each duplicate, or every second row to update it...
One way would be to use `group by` and `having`: ``` select max(id) id from table group by Prop1, Prop2 having count(*) > 1 ``` This would return the highest id for each duplicate group which with your sample data would be 2,4,6. This might, or might not be what you want - the question is a bit ambiguous. Note that...
Use `ROW_NUMBER` **[SqlFiddleDemo](http://sqlfiddle.com/#!6/ca4423/1/0)** ``` WITH cte AS ( SELECT Id ,[rn] = ROW_NUMBER() OVER(PARTITION BY Prop1, Prop2 ORDER BY Id) FROM your_tab ) SELECT Id FROM cte WHERE [rn] <> 1 ```
Select duplicates in SQL
[ "", "sql", "database", "t-sql", "" ]
I want table output as XML. My table result is [![enter image description here](https://i.stack.imgur.com/UUsJV.png)](https://i.stack.imgur.com/UUsJV.png) I need result like [![enter image description here](https://i.stack.imgur.com/LtbMo.png)](https://i.stack.imgur.com/LtbMo.png) Query ``` Declare @colorTable tab...
we have to write a query using `GROUP BY`, XML path not allowed to write sql within `xml path(not allowed select statement)` ``` Declare @colorTable table (Category varchar(100),Attribute varchar(100)) insert into @colorTable values ('Color','Red') insert into @colorTable values ('Color','Blue') insert into @colorTabl...
Finally I put code like this > Select Category as value , > (SELECT Attribute as value from @colorTable where Category= a.Category > FOR XML raw('attribute'), > TYPE) > from @colorTable as a group by Category > FOR XML raw('category'), ROOT ('xml'), type;
Xml output in SQL Server
[ "", "sql", "sql-server", "xml", "sql-server-2008", "stored-procedures", "" ]
I have a rather large statement that I've built up using an @SQL variable and then running the query from the variable at the end of the statement. This works fine except for when inserting a date into one of the parameters. The query then returns no data and come back with an error: > Conversion failed when converti...
It has already been pointed out that `@SessionStarted` is a `VARCHAR` when it should be a date. And that your final SQL is malformed, and no more valid than: ``` DECLARE @p3 DATE = GETDATE(); SELECT Test = @p3 '23:59:59'; ``` Which gives: > Msg 102, Level 15, State 1, Line 3 > > Incorrect syntax near '23:59:59'. Bu...
You have declared `sessionstarted` to be a character rather than a date. I imagine that this is the root cause of your problem. Change the type to a date. I would also recommend that you use ISO standard YYYY-MM-DD format for the date, rather than a culture-specific format.
How to express a BETWEEN statement in SQL when running query from a variable
[ "", "sql", "sql-server", "" ]
I want to achieve in MS SQL something like below, using 2 tables and through join instead of iteration. From table A, I want each row to identify from table B which in the list is their nearest value, and when value has been selected, that value cannot re-used. Please help if you've done something like this before. Th...
I highly believe **THIS IS NOT A GOOD PRACTICE** because I am bypassing the policy SQL made for itself that functions with side-effects (INSERT,UPDATE,DELETE) is a **NO**, but due to the fact that I want solve this without resulting to iteration options, I came up with this and gave me better view of things now. ``` c...
Below is a set-based solution using CTEs and windowing functions. The `ranked_matches` CTE assigns a closest match rank for each row in `TableA` along with a closest match rank for each row in `TableB`, using the `index` value as a tie breaker. The `best_matches` CTE returns rows from `ranked_matches` that have the b...
Left join with nearest value without duplicates
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have the following `IF` block that is supposed to be executed only if my table is empty. But it seems to be executing the code between `BEGIN` and `END` even when my table has a row. ``` IF ((SELECT COUNT(*) FROM [dbo].[KeyProperties]) = 0) BEGIN INSERT INTO [dbo].[KeyProperties] (KeyId,PropertyId) VALUES ((...
1) Use `NOT EXISTS` instead of counting and comparing to 0 2) Use `INSERT INTO tab(col) SELECT` ``` IF NOT EXISTS (SELECT 1 FROM [dbo].[KeyProperties]) BEGIN INSERT INTO [dbo].[KeyProperties] (KeyId,PropertyId) SELECT (SELECT Id FROM [dbo].[Keys] WHERE Priority=1), (SELECT Id FROM [dbo].[Propertie...
Use a variable instead: ``` DECLARE @Count INT (SELECT @Count = COUNT(*) FROM [dbo].[KeyProperties]) IF (@Count = 0) ``` or just ``` IF NOT EXISTS (SELECT TOP 1 NULL FROM [dbo].[KeyProperties]) ```
IF block executes when the condition does not apply
[ "", "sql", "sql-server", "database", "t-sql", "" ]
I'm trying to execute the following query as a simpler way to process several records rather than creating an insert statement for each individual one: ``` INSERT INTO wostatus (WO, STATUS, DATE, WOSTATUSID) SELECT workorder.wonum, 'CLOSE', '02-SEP-2015', (SELECT MAX(wostatusid) + 1 FROM wostatus) ...
use below query ``` INSERT INTO wostatus (WO,STATUS,DATE,WOSTATUSID) SELECT workorder.wonum, 'CLOSE', '02-SEP-2015', ((SELECT isnull(max(wostatusid),0) from wostatus)+ row_number() over(order by wostatus.wonum)) from wostatus join workorder on wostatus.wonum = workorder.wonum ```
You can use `ROW_NUMBER`: ``` INSERT INTO wostatus (WO,STATUS,DATE,WOSTATUSID) SELECT workorder.wonum, 'CLOSE', '02-SEP-2015', (SELECT max(wostatusid)+1 from wostatus) + ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) - 1 FROM wostatus JOIN workorder ON wostatus.wonum = workorder.wonum ```
SQL incremental id insert without auto key
[ "", "sql", "sql-server", "sql-server-2008", "" ]
How can I write a loop that runs n times in MySql without using a stored procedure. This is how I do it with a stored procedure: ``` DELIMITER $$ DROP PROCEDURE IF EXISTS test$$ CREATE PROCEDURE test() BEGIN DECLARE count INT DEFAULT 0; WHILE count < 10 DO /**Sql statement**/ SET count = count + 1; ...
MySQL docs on [Flow Control Statements](https://dev.mysql.com/doc/refman/5.6/en/flow-control-statements.html) say: > MySQL supports the IF, CASE, ITERATE, LEAVE LOOP, WHILE, and REPEAT > constructs for flow control **within stored programs**. Docs on [Stored Programs and Views](https://dev.mysql.com/doc/refman/5.6/en...
You can do it direcly with MariaDB Sequence Engine. MariaDB is a binary replacement for MySQL. **"A Sequence engine allows the creation of ascending or descending sequences of numbers (positive integers) with a given starting value, ending value and increment."** [Manual Sequence Engine] Here are some Samples: ``` ...
Loop n times without using a stored procedure
[ "", "mysql", "sql", "" ]
I have written the below query. However I am not able to get 0 in the corresponding counts. Can you please let me know how can i do join in this query to display 0's? ``` SELECT b.collected AS Last_Week_Collected, a.collected AS THIS_Week_Collected, b.errored AS Last_Week_Errored,...
Looking at your syntax, it looks like you are using a `Oracle` database. So, the `NVL` function should work for you just fine. Also, since you want to return `0`'s in place of null values, instead of `inner join`, you would want to do some form of `outer join` (either left, right, or full depending on your needs). If y...
You can do it using a conditional aggregate: ``` SELECT NVL(Last_Week_Collected, 0) AS Last_Week_Collected, NVL(THIS_Week_Collected, 0) AS THIS_Week_Collected, NVL(Last_Week_Errored, 0) AS Last_Week_Errored, NVL(THIS_Week_Errored, 0) AS THIS_Week_Errored, NVL(Last_Week_Processed, 0) AS...
SQL to display 0 in the counts
[ "", "sql", "" ]
I have the following table called Orders ``` Order | Date | Total ------------------------------------ 34564 | 03/05/2015| 15.00 77456 | 01/01/2001| 3.00 25252 | 02/02/2008| 4.00 34564 | 03/04/2015| 7.00 ``` I am trying to select the distinct order sum the total and group by order #, the...
``` SELECT [order], MAX(date) AS date, SUM(total) AS total FROM Orders o GROUP BY [order] ```
You can use the `MAX` aggregate function to choose the latest `Date` to appear from each `Order` group: ``` SELECT Order, MAX(Date) AS Date, SUM(Total) AS Total FROM Orders GROUP BY Order ```
Querying table with group by and sum
[ "", "sql", "sql-server", "t-sql", "" ]
This query ``` select distinct owner from dba_objects ``` is throwing this error ``` ORA-00942: table or view does not exist ``` Does that make any sense at all?
You have to use an administrative user (such as `sys` or `system`). If you do not have access to such a user, you could use the `all_objects` view instead of `dba_obejcts`. Any user can query it, and will get results only for the objects it has privileges to.
It does if you don't have select privs on the DBA\_OBJECTS view or if you don't have a local or global synonym to the SYS.DBA\_OBJECTS view. You could try selecting from SYS.DBA\_OBJECTS instead.
Getting Schemas from Oracle DB throwing error
[ "", "sql", "oracle", "select", "data-dictionary", "" ]
I have these table ``` Item +-------+--------+ | ID | Name | +-------+--------+ | 1 | itemA | +-------+--------+ Sales +-------+--------+-------------+-----+ | ID | ItemID | WarehouseID | ... | +-------+--------+-------------+-----+ | ABC | 1 | null | ... | +-------+--------+-------------+-...
You can use a `INNER JOIN` + `LEFT OUTER JOIN` for the `WarehouseId`: ``` SELECT item.ID as ItemID, item.Name as ItemName, sales.Id as SalesID, sales.WarehouseID, wh.Qty, wh.Price FROM Item INNER JOIN Sales ON item.ID = sales.ItemID LEFT OUTER JOIN Warehouse wh ON sales.WarehouseID = wh...
Eh, something like that? ``` select i.ID as ItemID, i.Name as ItemName, s.ID as SalesID, w.ID as WarehouseID, w.Qty as Qty, w.Price as Price from (Item i join Sales s on i.Id = s.ItemID) left join WareHouse w on w.ItemId = i.ID and w.SalesID = s.ID ``` *inne...
SQL command to Retrieve data where one column is null
[ "", "sql", "" ]
How can I use a CASE that will affect which column will be updated? ``` UPDATE TABLE1 CASE WHEN [Status] = 'Alpha' THEN AlphaStatus = Status ``` Using the solution [here](https://stackoverflow.com/questions/4830191/t-sql-using-a-case-in-an-update-statement-to-update-certain-columns-depending-o), I tried something...
By separating each field into a different join, you can do it in a single update. ``` update t set AlphaStatus = ISNULL(rA.[Status], AlphaStatus), BetaStatus = ISNULL(rB.[Status], BetaStatus), GammaStatus = ISNULL(rG.[Status], GammaStatus) from @Table t left join @Values rA on rA.id = t.ID AND rA.[Group] ...
You could write this in two separate ways: **First Method:** ``` UPDATE t SET t.AlphaStatus = coalesce(ra.[Status], t.AlphaStatus) ,t.BetaStatus = coalesce(rb.[Status], t.BetaStatus) ,t.GammaStatus = coalesce(rg.[Status], t.GammaStatus) FROM @Table t LEFT JOIN @values ra ON ra.id = t.ID AND ra.[group] = '...
CASE in UPDATE that determines column to update?
[ "", "sql", "sql-server", "t-sql", "" ]
I want to generate an XML element using Oracle's XML documentation generation support features that looks like this ``` <Example Attr=""></Example> ``` Attr is an attribute of element Example and has a value of empty string "". When I tried to generate an XML Element using Oracle's XML functions, I couldn't generate...
As you're aware, for XMLAtttribute ["if the value\_expr is null, then no attribute is created for that value expression"](http://docs.oracle.com/cd/E11882_01/server.112/e41084/functions242.htm#SQLRF06168). You can work around this with [InsertChildXML](http://docs.oracle.com/cd/E11882_01/appdev.112/e23094/xdb04cre.htm...
What about setting the property value to some impossible value and then replace it with the value you need (so, empty string in your case)? ``` select replace( XMLELEMENT("hello", xmlattributes('$$IMPOSSIBLE-VALUE$$' as "Max")).getStringVal(), '$$IMPOSSIBLE-VALUE$$' ) from dual; ``` I assume you anyway in the e...
How to generate XML data in Oracle which has Empty string as an attribute
[ "", "sql", "xml", "oracle", "" ]
I need to find the highest-valued row in each group in a table, e.g., I want to group the following by Color and Shape, and then take the row with the highest Cost. E.g. for input ``` ID Color Shape Cost -- ----- ----- ---- 1 Red Round 45 2 Red Round 18 3 Red Square 13 4 Red Square 92 5 Gr...
You can use `row_number` to partition on color and shape and then assign 1 as row number to the highest cost in that partition. ``` select id,color,shape,cost from ( select *, row_number() over(partition by color,shape order by cost desc) as rn from tablename ) t where rn = 1; ```
This should be a straight forward SELECT statement if you have your table setup - we'll call it table\_a: ``` SELECT id, color, shape, max(cost) as Cost from table_a group by id, color, shape ``` Not sure about the output allowing for Cost to be capitalized in your output - sometimes this depends on your SQL Syntax. ...
Return highest-ranked row in each group
[ "", "sql", "t-sql", "plsql", "" ]
I am trying to create a while loop in SQL and it seems kind of complex. Here's what I need it to achieve: 1. Iterate through a single VARCHAR string (ex. '123') 2. If the nth character is in an even position in the string (ex. 2nd, 4th .... letter in the string), it must be added(SUM) to a base variable (Let's assume ...
You can do this without using a loop. Here is a solution using Tally Table: ``` DECLARE @x VARCHAR(20) = '12345' DECLARE @z INT = 0 -- base value ;WITH E1(N) AS( -- 10 ^ 1 = 10 rows SELECT 1 FROM(VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))t(N) ), E2(N) AS(SELECT 1 FROM E1 a CROSS JOIN E1 b), -- 10 ^ 2 = 100 r...
Check below if it helps you ``` DECLARE @x varchar(20) = '12345' DECLARE @p int = 1 DECLARE @result bigint=0; DECLARE @tempval int =0; WHILE @p <= len(@x) BEGIN SET @tempval = CONVERT(INT,substring(@x, @p, 1)); if(@p%2 = 1) BEGIN SET @tempval = @tempval * 2; IF(@tempval >= 10) SET @tempval = @tempval - 9;...
Complicated SQL while loop
[ "", "sql", "sql-server", "" ]
I'm working in an Oracle environment. In a 1:M table relationship I want to write a query that will bring me each row from the "1" table and **only 1 matching row** from the "many" table. To give a made up example... ( \* = Primary Key/Foreign Key ) ``` EMPLOYEE *emp_id name department PHONE_NUMBER *emp_id num ``` ...
If you want only one phone number, then use `row_number()`: ``` SELECT e.*, p.num FROM EMPLOYEE emp JOIN (SELECT p.*, ROW_NUMBER() OVER (PARTITION BY emp_id ORDER BY emp_id) as seqnum FROM PHONE_NUMBER p ) p ON e.emp_id = p.emp_id and seqnum = 1; ``` Alternatively, you can use aggrega...
All above answers will work beautifully with the scenario you described. But if you have some employees which are missing in phone tables, then you need to do a left outer join like below. (I faced similar scenario where I needed isolated parents also) ``` EMP --------- emp_id Name --------- 1 AA 2 BB 3 CC ...
Limit the data set of a single table within a multi-table sql select statement
[ "", "sql", "oracle", "join", "rownum", "" ]
I have the following mysql table: ``` CREATE TABLE test (id INT, _id INT, name VARCHAR(30), age INT); INSERT INTO test (id, _id, name, age) VALUES (1, 1, 'Lorem', 20), (2, 1, 'Ipsum', 21), (3, 1, 'Dolor', 22), (4, 1, 'Sit', 23), (5, 1, 'Amet', 2...
You can use the following query: ``` SELECT t2.id AS min_id, t3.id AS max_id, t1._id, t2.name AS first_name, t3.name AS last_name, t2.age AS first_age, t3.age AS last_age FROM ( SELECT _id, MIN(age) AS minAge, MAX(age) AS maxAge FROM test GROUP BY _id ) AS t1 INNER JOIN test AS t2 ON t2.age = t...
This will give the first result: ``` SELECT id, _id, name, age FROM test WHERE id IN (SELECT MIN(id) FROM test GROUP BY _id) OR id IN (SELECT MAX(id) FROM test GROUP BY _id) ```
How to get first and last records grouping by a certain column?
[ "", "mysql", "sql", "group-by", "" ]
I want to lookup values listed in a temp table: So let us say: ``` Create Table #mylist ( eserial nvarchar(35) Collate SQL_Latin1_General_CP850_CI_AS, refdate datetime ) Insert Into #mylist (eserial, refdate) Values ('A', '2015-09-15') Insert Into #mylist (eserial, refdate) Values ('B', '2015-09-14') Insert Into #my...
It is not quite clear what you mean by > maintain the sequence of the items in the temporary table , but if you want to get result ordered by `eserial`, then you have to add `ORDER BY eserial` to your query. Without `ORDER BY` the resulting rows can be returned in any order. This applies to any method that you choose...
That's easy using identity. Query without `Order` is not guarantee to have order in SQL server. ``` Create Table #mylist ( seqId int identity(1,1), eserial nvarchar(35) Collate SQL_Latin1_General_CP850_CI_AS, refdate datetime ) ``` Use the table freely and put `Order By seqId` at the end of your query **...
Pull data without altering the item sequence in the reference table
[ "", "sql", "sql-server", "sql-server-2008-r2", "" ]
I want to extract the string after the character '/' in a PostgreSQL SELECT query. The field name is `source_path`, table name is `movies_history`. Data Examples: Values for source\_path: * 184738/file1.mov * 194839/file2.mov * 183940/file3.mxf * 118942/file4.mp4 And so forth. All the values for source\_path are i...
If your case is that simple (*exactly* one `/` in the string) use [`split_part()`](https://www.postgresql.org/docs/current/functions-string.html#FUNCTIONS-STRING-OTHER): ``` SELECT split_part(source_path, '/', 2) ... ``` **If** there can be *multiple* `/`, and you want the string after the *last* one, a simple and fa...
You need use [*substring*](http://www.postgresql.org/docs/9.1/static/functions-string.html) function [**SQL FIDDLE**](http://sqlfiddle.com/#!15/9eecb7db59d16c80417c72d1e1f4fbf1/2989) ``` SELECT substring('1245487/filename.mov' from '%/#"%#"%' for '#'); ``` Explanation: ``` %/ ``` This mean `%` some text and then a...
Get string after '/' character
[ "", "sql", "regex", "postgresql", "pattern-matching", "" ]
I am using Microsoft Access 2010 and I have a table `T_Offers` that looks like this: ``` Key ID Date Name Text --- -- ---------- ----------- ----------- 1 10 10/10/2015 Lorem Consectetur 2 10 10/10/2015 Ipsum Amet 3 11 27/09/2014 ...
You can use `NOT EXISTS` to exclude all rows where another row with the same ID and an earlier date exists: ``` SELECT t1.Key, t1.ID, t1.Date, t1.Name, t1.Text FROM t_offers AS t1 WHERE NOT EXISTS ( SELECT 1 FROM T_Offers AS t2 WHERE t2.ID = t1.ID AND t2.Da...
You need a select distinct query: ``` SELECT DISTINCT ID, name, text, MIN (date) AS minDate FROM T_Offers GROUP BY ID, name, text ORDER BY ID asc; ```
Select only one row from a group by?
[ "", "sql", "database", "ms-access-2010", "" ]
I want to list the all tables and each tables count columns and each table count of (primary+foreign key) used in my DB EG: table 1 contain 2 columns and one primary key then result should be like below ``` Tables List Total columns Primary+foreign Key count 1 2 1 ```
Try this ``` SELECT C.TABLE_NAME, Count(C.COLUMN_NAME) AS TOTAL, Count (A.COLUMN_NAME) AS [PRIMARY+FORIGN KEY COUNT] FROM INFORMATION_SCHEMA.COLUMNS C LEFT OUTER JOIN (SELECT DISTINCT TC.TABLE_NAME, COLUMN_NAME FROM INFORMATION_S...
with the help of [Information Schema](https://msdn.microsoft.com/en-in/library/ms186778.aspx) ``` -- All info SELECT * FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE ORDER BY TABLE_NAME --Count Info SELECT table_name,count(column_name) ColCount,count(constraint_name) ConstraintCount FROM INFORMATION_SCHEMA.KEY_COLUMN_USAG...
List of Tables and total columns and count of primary and foreign keys
[ "", "sql", "sql-server", "" ]
I am trying to run this query but I am getting a **Missing Expression error**. ``` SELECT * FROM ( SELECT ROW_NUMBER() OVER(order by 'rownum') row_num1, * FROM A WHERE refresh_date = ( SELECT max(refresh_date) FROM A WHERE upper(flaw_table_name) = upper('B') ...
you have to add an alias, you cannot use \* without a name if you're using other colnames or functions too ``` SELECT * FROM (SELECT row_number() over(ORDER BY 'rownum') row_num1, t.* FROM a t WHERE refresh_date = (SELECT MAX(refresh_date) FROM a ...
You have a constant in the `order by` clause. In addition, it is redundant to put `rownum` there in the first place. Just use `rownum`. I think you want: ``` SELECT A.* FROM A WHERE refresh_date = (SELECT max(refresh_date) FROM A WHERE upper(flaw_table_name) = upper('...
Missing Expression for the Oracle query
[ "", "sql", "oracle", "window-functions", "" ]
Apologies if this has already been asked, but I can't find how to do this. I have this table: ``` ID Col1 Col2 Col3 Col4 Col5 Col6 ------------------------------------------------------ 1 1a 1b 1c 1d 1e 1f 2 2a 2b 2c 2d 2e 2f 3 ...
You can use Unpivot. ie: ``` SELECT ColName FROM myTable UNPIVOT ( COLName FOR col IN ( Col1, Col2, Col3, Col4, Col5, Col6 ) ) AS unpvt; ```
you can achieve this with the help of [UNPIVOT](https://technet.microsoft.com/en-us/library/ms177410%28v=sql.105%29.aspx) ``` -- Row to multiple column declare @Data TABLE (Id INT, Col1 VARCHAR(20) , Col2 VARCHAR(20), Col3 VARCHAR(20), Col4 VARCHAR(20)) INSERT INTO @Data VALUES (1 , '1a', '1b' ,'1c','1d'), (2 , ...
Consolidate multiple columns into single column
[ "", "sql", "sql-server", "" ]
I am trying to figure out a way in Hive to select data from a flat source and output into an array of named struct(s). Here is a example of what I am looking for... Sample Data: ``` house_id,first_name,last_name 1,bob,jones 1,jenny,jones 2,sally,johnson 3,john,smith 3,barb,smith ``` Desired Output: ``` 1 [{"first...
I would use this [jar](https://github.com/klout/brickhouse/blob/master/src/main/java/brickhouse/udf/collect/CollectUDAF.java), it is a much better implementation of `collect` (and takes complex datatypes). **Query**: ``` add jar /path/to/jar/brickhouse-0.7.1.jar; create temporary function collect as 'brickhouse.udf.c...
You can also use a workaround ``` select collect_list(full_name) full_name_list from ( select concat_ws(',', concat("first_name:",first_name), concat("last_name:",last_name) ) full_name, house_id from house) a group by house_id ```
Hive select data into an array of structs
[ "", "sql", "hadoop", "hive", "apache-pig", "hiveql", "" ]
I have a pretty large database of 20 million records of geographic points, and its growing every day. ``` [id (int)] [group (int)] [latitude (double)] [longitude(double)] [1] [1] [22.365598] [12.55678] [2] [1] [22.365548] [12.55238] [3] [2] [24.665348]...
As documented under [The Range Access Method for Multiple-Part Indexes](https://dev.mysql.com/doc/en/range-optimization.html#range-access-multi-part): > The optimizer attempts to use additional key parts to determine the interval as long as the comparison operator is [`=`](https://dev.mysql.com/doc/en/comparison-opera...
First, parentheses don't matter for `distinct`. So, just write the query as: ``` SELECT distinct `group`, id from `table` where latitude between -95.22 and 36.458 and longitude between -51.939 and 103.833; ``` This type of query -- with two `between`s -- is not really amenable to indexes. You *can* try an index...
Speeding up this mysql query
[ "", "mysql", "sql", "database", "" ]
I have six different select statements used for SSRS reporting purpose. Below are two statements out of those. I need help on how to do `Union All` for bellow and combine all statements into one. ``` DECLARE @FromDate AS DATE='04-Aug-2015' DECLARE @ToDate AS DATE='05-Aug-2015' SELECT A.LBrCode AS BranchCode, ...
You can only apply one `ORDER BY` clause to affect the order of results, and it has to apply to the entire result set. If, as I suspect, you want all of the results from the top query to appear before results from the bottom query, you need to add another column to the data to allow that to happen: ``` SELECT A.LBrCod...
For a union to work both queries must have the same number of columns and be compatible data types, you may want to convert column data types to ensure they are the same. For example you may have issues with your Amount and Balance columns of the data types are incompatible. You cannot order each individual statement ...
Union All Help Needed
[ "", "sql", "sql-server", "" ]
I have been trying to develop a query to solve a problem but its been hard. Table 1: ``` +------+----+ | NAME | ID | +------+----+ | A | 1 | | A | 2 | | B | 1 | | B | 5 | | C | 8 | +------+----+ ``` Table 2: ``` +------+----+ | NAME | ID | +------+----+ | A | 1 | | A | 4 | | B | 3 | ...
You might wanna try this: EDIT: replaced table1 and table2 with a simple subqueries in WITH clause. ``` WITH table1 AS ( SELECT DECODE(LEVEL,1, 'A',2, 'A',3, 'B',4, 'B',5, 'C') AS name ,DECODE(LEVEL,1, 1,2, 2,3, 1,4, 5,5, 8) AS id FROM dual CONNECT BY LEVEL < 6 ) ,table2 AS ( SELECT DECODE(LEVEL,1, 'A',2, 'A'...
I would do: ``` with t1 as (select 'A' name, 1 id from dual union all select 'A' name, 2 id from dual union all select 'B' name, 1 id from dual union all select 'B' name, 5 id from dual union all select 'C' name, 8 id from dual), t2 as (select 'A' name, 1 id from du...
Return from Table 2 different Ids from same names on Table1
[ "", "sql", "oracle", "inner-join", "outer-join", "" ]
Using Microsoft SQL Server, Table1 has customer requests, table2 has a resolution code (so we can see why customers are writing in, and what we did to resolve their issue). Sometimes reps forget to add the resolution code, so I'm trying to run a query to tell me the name of each rep, how many closed issues are missing ...
``` select t1.assigned_to, t1.missing, t2.total from ( select i.assigned_to as assigned_to, count(i.assigned_to) as missing from customer_issues as i left join resolution_codes as r on i.issue_ID = r.issue_ID where r.issue_id is null and i.status='closed' group by i.assigned_to ) t1 INNER JOIN ( select assigned_to, c...
Since the only difference between the two queries seems to be the left join and null filter you can do it all in one query. This should work I think: ``` ;with source as ( select i.assigned_to as [Agent Name], count(r.issue_id) as [Resolution Codes], count(i.assigned_to) as [Total issues...
query the same table twice to get different numbers in one query
[ "", "sql", "sql-server", "" ]
I already have values in a temp table and I want to insert it into my table. I follow this syntax ``` IF NOT EXISTS (SELECT 1 FROM ABC abc JOIN #Temp t ON abc.ID = t.ID) insert into MyTable(Id,Name) select values (t.ID, t.Name) From t ``` I have just the name t as an alias I created in a condition before this inser...
Correct syntax: ``` insert into MyTable(Id,Name) select t.ID, t.Name From #temp t ``` Always [read manual](https://technet.microsoft.com/en-us/library/dd776381%28v=sql.105%29.aspx)
You can check this ``` insert into Table1(Id,Name) select ID,Name From t ```
How to insert into a table from temp table?
[ "", "sql", "sql-server", "sql-server-2008", "temp-tables", "" ]
I'm trying to update a table called `incode_warrants` and set the `warn_docket_no` to the `viol_docket_no` from the `incode_violations` table. I have the following SQL query in Postgres 9.3, but when it fires I get the following error: > ``` > Error : ERROR: relation "iw" does not exist > LINE 1: update iw > ``` I'...
The same as valid `UPDATE` statement in Postgres: ``` UPDATE incode_warrants iw SET warn_docket_no = iv.viol_docket_no FROM incode_warrantvs iwvs JOIN incode_violations iv ON iv.viol_citation_no = iwvs.warnv_citation_no AND iv.viol_viol_no = iwvs.warnv_viol_no WHERE iw.warn_rid = iw...
Your query should look like this: ``` UPDATE incode_warrants SET warn_docket_no = incode_violations.viol_docket_no FROM incode_violations WHERE incode_violations.viol_citation_no = incode_warrants.warnv_citation_no AND incode_violations.viol_viol_no = incode_warrants.warnv_viol_no; ``` You don't need any other join. ...
UPDATE statement with multiple joins in PostgreSQL
[ "", "sql", "postgresql", "sql-update", "inner-join", "" ]
i want to do something like that: ``` Select (select sum(monkey_value) from mt where monkey_weight > 20) , (select sum(monkey_value) from mt where monkey_weight > 30) from MonkeyTable mt where monkeySanityLevel > 10 ``` but i cant use mt in subselects. What ive done right now is that i declared an table and pass th...
How about ``` Select Sum(case when monkey_weight > 20 then monkey_value else 0 end) as WT20, Sum(case when monkey_weight > 30 then monkey_value else 0 end) as WT30 from MonkeyTable mt where monkeySanityLevel > 10 ```
following should work: ``` select sum(case when monkey_weight > 20 then monkey_value end) as monkey_weight_20, sum(case when monkey_weight > 30 then monkey_value end) as monkey_weight_30 from MonkeyTable mt where monkeySanityLevel > 10 ```
How to use parent result in sub selects?
[ "", "sql", "sql-server", "" ]
I want to concatenate two dates with their times like below in SQL Server 2008. Something like this: ``` 2015-09-09 08:30 - 2015-09-09 09:30 ``` I tried this method but didn't work and I used casting as well. ``` CONVERT(DATETIME, CONVERT(CHAR(8), S.StartTime, 112)+ '-' + CONVERT(CHAR(8), S.endtime, 108)) AS 'Occupi...
``` CONVERT(CHAR(16), s.StartTime, 120) + '-' + CONVERT(CHAR(16), s.EndTime, 120) AS OccupiedTime ```
You need 2 parts of date - date only + time. You can have 2 strings and concatenate them: ``` SELECT REPLACE(CONVERT(VARCHAR(50),s.StartTime,103),'/','-') + ' ' + CONVERT(VARCHAR(5),s.StartTime,114) + ' - ' + REPLACE(CONVERT(VARCHAR(50),s.EndTime,103),'/','-') + ' ' + CONVERT(VARCHAR(5),s.EndTime,114) AS ...
Concatenate Two dates and their times in SQL Server 2008
[ "", "sql", "sql-server", "sql-server-2008", "datetime", "stored-procedures", "" ]
I have been working on a query (in sql Server TSQL) which fills left of a number with 0's so output is always 5 digit. So: ``` Select MuNumber From Mytable ``` for data 11,011,2132,1111 ``` Creates output like 00011 02134 01111 ``` I tried Lpad Function but numer of 0's can be different. if Munumber is 1 we need...
Assuming that MuNumber is VARCHAR simply use `RIGHT` ``` SELECT RIGHT('00000' + MuNumber, 5) FROM Mytable ``` Otherwise you need to convert it first ``` SELECT RIGHT('00000' + CONVERT(VARCHAR(5), MuNumber), 5) FROM Mytable ``` And in general you can use this pattern: ``` DECLARE @num INT = 10; SELECT RIGHT(REPLIC...
Try this ``` select right('00000'+cast(col as varchar(5)),5) from table ```
Query to pad left of a field with 0's
[ "", "sql", "sql-server", "t-sql", "" ]
I have table name `Sample` with the columns `Id` and `Position`. ``` select ID ,POSITION from SAMPLE order by 1 ``` Sample : ``` ID Position 1 GEN2 1 GEN1 2 GEN1 2 GEN4 2 GEN2 2 GEN3 3 GEN1 4 GEN1 5 GEN1 5 GEN1 5 GEN1 5 GEN4 6 GEN1 ``` Here I need to select the records based on the below...
If you have a `history_id`, you can use `row_number()`: ``` select h.* from (select h.*, row_number() over (partition by id order by history_id desc) as seqnum from history h ) h where seqnum = 1 and Position = 'GEN1'; ```
Use `row_number()` partitioned by `id` and order by `history_id` int descending order in a common table expression: ``` WITH CTE AS ( SELECT rn = ROW_NUMBER() OVER (PARTITION BY ID ORDER BY History_id DESC) , * FROM Sample ) SELECT * FROM CTE WHERE Position = 'GEN1' AND rn = 1; ``` An alternativ...
Filter SQL Query based on Last Values in the resultset
[ "", "sql", "sql-server", "" ]
I have table in my database with next SQL code ``` CREATE TABLE `table` ( `id` INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL, `column1` VARCHAR(255) NOT NULL, `column2` INTEGER NULL, `column3` INTEGER NULL, `column4` INTEGER NULL, `default` INTEGER NULL ); ``` And i can insert data into it with ``` INSERT INTO `t...
Try escaping the column name `default` with backticks, like you have with the table name.
do the same thing that you did on your table: ``` INSERT INTO `table` (`id`,`column1`,`default`) VALUES (1,'something',1), ```
How to insert data into database with column name "default"
[ "", "mysql", "sql", "" ]
I have following database tables in SQL Server 2008. ``` customer ------------ id, Name, Address payment ------- payment_id, amount, customer_id Sales S_id, Date, ItemName, amount, commission, customer_id ``` I am novice to SQL queries. i want want to to display result ``` name, previous customer balance i.e (sum(...
Something like the below should work: ``` select c.[Name], saleSum.SaleTotal - paymentSum.PaymentTotal from customer c join ( select c.[id], sum(isnull(s.amount,0) + isnull(s.commission, 0)) SaleTotal from customer c left join sales s on c.id = s.customer_id group by c.[id] ) as saleSum on c.id = saleSum.id join ( se...
The equery is ``` Select Tab1.ID, Min(Tab1.name), sum(Tab3.amount) + Sum(Tab3.commission) - sum(Tab2.amount) From Table1 Tab1 inner join Table2 tab2 on Tab1.id = Tab2.customer_id inner join Table3 tab3 on Tab1.id = Tab3.customer_id Group by Tab1.ID ```
Finding Sum of all previous sales to all customer and sum of today's sale in sql query
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have one table (TransactionData) containing transaction data for customers and one table (Subscribers) containing customers that are newsletter subscribers. This is what I need to do. Select all subscribers from TransactionData table that are also in the Subscribers table and that has only purchased products online ...
``` SELECT t.Email , t.StoreID FROM TransactionData t WHERE EXISTS (SELECT 1 FROM Subscribers WHERE t.Email = Email) AND NOT EXISTS (SELECT 1 FROM TransactionData WHERE t.Email = Email AND StoreID <> 50001) GROUP BY t.Email , t.StoreID ```
``` declare @TransactionData TABLE ([Email] varchar(18), [StoreID] int, [OrderID] int) ; INSERT INTO @TransactionData ([Email], [StoreID], [OrderID]) VALUES ('customer1@mail.com', 50001, 101), ('customer1@mail.com', 50001, 102), ('customer2@mail.com', 50001, 201), ('customer2@mail.com', 51111,...
SQL server – get rows with customers that has only purchased online
[ "", "sql", "sql-server", "" ]
I am having problems in the next query: This is my array of data ``` String[] columns = new String[] { KEY_ROWELEMENTID, KEY_STUDYID, KEY_ELEMENTCODE, KEY_ELEMENTNAME}; ``` I create a cursor to this array where: The column KEY\_ELEMENTCODE is equal to a varable result AND KEY\_STUDYID is equal to a varable result ...
Yes there should be space as " AND ", One more thing, if you are comparing for Integer values then use this line, ``` Cursor c = ourDatabase.query(DATABASE_TABLEELEMENTS, columns, KEY_ELEMENTCODE + "=" + elementRequest + " AND " + KEY_STUDYID + "=" + idStudy, null, null, n...
Without seeing the output from ``` KEY_ELEMENTCODE + "=" + elementRequest + "AND" + KEY_STUDYID + "=" + idStudy ``` I guess that you just have to replace ``` "AND" ``` with ``` " AND " ```
Unrecognized token AND
[ "", "android", "sql", "sqlite", "token", "" ]
I need to show a list of partners and the maximum value from the `reservation_limit` column from `Klass` table. ``` Partner has_many :klasses Klass belongs_to :partner # Partner controller def index @partners = Partner.includes(:klasses) end # view <% @partners.each do |partner| %> Up to <%= partner.klas...
You can use two forms of SQL to efficiently retrieve this information, and I'm assuming here that you want a result for a partner even where there is no klass record for it The first is: ``` select partners.*, max(klasses.limit) as max_klasses_limit from partners left join klasses on klasses.partner...
Your initial query brings all the information you need. You only need to work with it as you would work with a regular array of objects. Change ``` Up to <%= partner.klasses.maximum("reservation_limit") %> visits per month ``` to ``` Up to <%= partner.klasses.empty? ? 0 : partner.klasses.max_by { |k| k.reservation_...
Rails: Optimize querying maximum values from associated table
[ "", "sql", "ruby-on-rails", "ruby", "postgresql", "rails-postgresql", "" ]
Consider the following 2 tables: ``` customer( **c_id**, c_name, c_dob) customer_loan_taken( **loan_no**, c_id, taken_date, loan_amount) ``` How to find out average loan taken by age group 20-25, 30-35, 40-45, and display them in a single table ? The table contents are as follows: ## customer table ``` C_ID C_NA...
This is working in Oracle 12c. The trick to figure out the age can differ on database as datediff is not working in oracle. So modify it accordingly ``` with customer( c_id, c_name, c_dob) as (select 1,'A','31/01/1990' from dual union select 2,'A','31/01/1980' from dual union select 3,'C','31/0...
``` ;WITH cte AS ( SELECT CASE WHEN DATEDIFF ("YY", c_dob, GETDATE()) > 20 AND DATEDIFF ("YY", c_dob, GETDATE()) <= 25 THEN '20-25' WHEN DATEDIFF ("YY", c_dob, GETDATE()) > 25 AND DATEDIFF ("YY", c_dob, GETDATE()) <= 30 THEN '25-30' ...
Find out average loan taken by age group in specific ranges and display them in a table
[ "", "sql", "oracle", "oracle12c", "" ]
I have a scenario where I have 2 tables with the same foreign key and amount column, such as below: ``` TABLE 1: ForeignKey Amount ---------- ------------- 12 20.0 12 30.0 13 20.0 21 10.0 21 10.0 TABLE 2: ForeignKey Amount ---------- ...
``` SELECT t1.ForeignKey, t1.total AS total1, t2.total AS total2, t1.total-t2.total AS difference FROM ( SELECT ForeignKey,sum(Amount) AS total FROM table1 GROUP BY ForeignKey ) t1 INNER JOIN ( SELECT ForeignKey,sum(Amount) AS total FROM table2 GROUP BY ForeignKey ) t2 ON t1.ForeignKey=t2...
``` ;with t as (select ForeignKey,amount from [table 1] union select ForeignKey,-amount from [table 2]) select ForeignKey,sum(amount) from t group by ForeignKey ```
Compare columns from 2 different tables and get the difference in amount
[ "", "sql", "" ]
I've this table with the following data ``` id Product Price 1 ELECTRO TV 2 null null 3 null null 4 Samsung 1000 5 LG 2000 6 Philips 1300 7 ELECTRO Mobile 8 null null 9 null null 10 Samsung 1000 11 Nokia 2...
[SQL Fiddle](http://sqlfiddle.com/#!4/3a235/2) **Oracle 11g R2 Schema Setup**: ``` CREATE TABLE test (id, Product, Price ) AS SELECT 1, 'ELECTRO', 'TV' FROM DUAL UNION ALL SELECT 2, null, null FROM DUAL UNION ALL SELECT 3, null, null FROM DUAL UNION ALL SELECT 4, 'Samsung', '1000' ...
There appear to be a number of things wrong with the design of your data here, and I really think that you need to address them before trying to make your query. For starters, it looks like Electro is a category, and should therefore be a column, but Product is already doing the work, which makes Electro in any form lo...
repeat a value of a row in a new column
[ "", "sql", "oracle", "oracle11g", "" ]
I have the following situation: One table called cad (id, name, gender, age, fok\_professional, fok\_agegroup, fok\_ativity) and other table called professional (id, name), agegroup (id, desc), ativity (id, name); How to select the name value instead number as generally is presented in simple query: For exemple: ``` S...
You want something like this, using SQL JOINs to connect the tables together : ``` SELECT cad.id, cad.name, cad.gender, cad.age, professional.name, agegroup.desc, ativity.name FROM cad INNER JOIN professional ON cad.fok_professional = professional.id INNER JOIN agegroup ON cad.fok_agegroup = agegr...
You need to use inner join between those three tables. Try this: ``` SELECT C.ID, C.NAME, C.GENDER, C.AGE, P.NAME AS [FOK_PROFESSIONAL], A.DESC AS [FOK_AGEGROUP], AT.NAME AS [FOK_ATIVITY] FROM CAD C INNER JOIN PROFESSIONAL P ON C.FOK_PROFESSIONAL = P.ID INNER JOIN AGEGROUP A ON C.FOK_AGEGROUP = A.ID INNER JOIN ATIVITY...
How to Select foreign key names instead of number in SQL Server
[ "", "sql", "sql-server", "database", "" ]
Similarly to [this question](https://stackoverflow.com/q/9325762) I would like to perform an SQL "like" operation using my own user defined type called "AccountNumber". The QueryDSL Entity class the field which defines the column looks like this: ``` public final SimplePath<com.myorg.types.AccountNumber> accountNumbe...
In the end, I was given a tip by my colleague to do the following: ``` if (pRegion != null) { expressionBuilder.and(Expressions.booleanTemplate("{0} like concat({1}, '%')", qBusinessEvent.accountNumber, pRegion)); } ``` This seems to do the trick!
Did you try using a String constant instead? ``` Path<?> path = QBusinessEvent.businessEvent.accountNumber; Expression<String> constant = Expressions.constant(pRegion.toString()); Predicate predicate = Expressions.predicate(Ops.STARTS_WITH, path, constant); ```
QueryDSL like operation SimplePath
[ "", "sql", "jpa", "sql-like", "querydsl", "" ]
I am using SQL Server 2012. I have written the query below which works fine apart from when I include the last line 'where NomDiff <> 0'. It tells me NomDiff is an invalid column name. I don't understand why and don't know how to get the query to return only rows where the nomDiff is not equal to zero? ``` ;with pf ...
Using `APPLY VALUES` is a good way of not having to use a subquery, or another CTE: ``` WITH pf AS ( SELECT Name , Sedol , Nominal FROM tblTempPLF WHERE FundCode = 'CSGE' ), pc AS ( SELECT Name , Sedol , Nominal FROM tblTempPCF WHERE FundCode = 'BTCM' ...
You can't use a previously defined `alias` in the `where` clause. Use the calculation instead. ``` select coalesce(pf.Name, pc.Name) Name, coalesce(pf.Sedol, pc.Sedol) Sedol, isnull(pf.Nominal,0) PfNom, isnull(pc.Nominal,0) PcNom, isnull(pf.Nominal,0) - isnull(pc.Nominal,0) NomDiff from pf full outer join pc on p...
using where clause causes invalid column name error
[ "", "sql", "sql-server", "sql-server-2012", "" ]
I'm doing this challenge on Hackerrank: <https://www.hackerrank.com/challenges/weather-observation-station-5> I'm a beginner on SQL and I'm trying to query all the rows that have a maximum value for a column, maximum that I can only obtain via `MAX()`. So I'm trying this: ``` SELECT CITY, LENGTH(CITY) AS citylength ...
This works without sub-queries ``` SELECT CITY, LENGTH(CITY) FROM STATION ORDER BY 2,1 LIMIT 1 ```
You are requested to find two different results: * The city with maximum length (and the first in the alphabet in case of a tie) * The city with minimum length (and the first in the alphabet in case of a tie) This means two different queries, which you glue together with UNION ALL. ``` ( select concat(city, ' ', l...
How to select rows that have a maximum value for a column
[ "", "mysql", "sql", "" ]
I'm trying to select the sum of the values in the `isOK` column for each `Name` separated, BUT only if `isOK = 1` on `Day = 2`. The query for the following example table `tablename` ``` Name | Day | isOK char | int | int ----------------- Flo | 1 | 1 Seb | 1 | 1 Tim | 1 | 0 Flo | 2 | ...
One way to do this is to use a conditional expression together with a `having` clause like this: ``` select name, sum(isOk) ok_sum from your_table group by name having sum(case when day = 2 and isOK = 1 then 1 else 0 end) > 0; ``` With your sample data the result would be: ``` name ok_sum Flo 2 Tim 1 ``` ...
TRY this : ``` SELECT name, SUM(isok) AS isOk FROM table GROUP BY `name` HAVING SUM(`day` = 2 AND isok = 1) > 0; ```
Aggregate rows if one row meets a specific condition
[ "", "mysql", "sql", "conditional-statements", "" ]
So I have two tables. `Table 1` ``` ID Receiver Some Columns 1 43523 Ba Baa 2 82822 Boo Boo ``` `Table 2` ``` ID Receiver Some2 Columns2 1 - 43523 OO JJ 2 - 43523 OO NULL 3 - 43523 OO YABA DABA ``` So, Now I want to do a `left join` where in I join only one of the matching rows from tabl...
You can change your `left join` to a normal `join`, since you are always expecting a match. And to limit the matches to a single row, you can use `row_number over ()`, where the `order by` clause is meaningless, since you don't care which row you are matching to. ``` SELECT Table1.[ID], Table1.[Receiver], ...
Try using a `group by` to make the `Receiver` column unique: ``` SELECT t1.*, t2.* FROM Table1 AS t1 LEFT JOIN Table2 AS t2 ON t1.Receiver = t2.Receiver GROUP BY t2.Receiver ```
Trying to do a LEFT JOIN on two tables but want only one from the RIGHT TABLE
[ "", "sql", "join", "left-join", "" ]
I have a rails model call MentorData and it has an attribute called `os_usage`. The oses are stored in an array like so `['apple', 'linux']`. To recap: ``` $ MentorData.first.os_usage => ['apple', 'linux'] ``` I am looking to be able to query the data for all MentorData that includes the os\_usage of `apple`, but w...
Here are the examples given in the current [Rails Edge Guides](http://edgeguides.rubyonrails.org/active_record_postgresql.html) for PostgreSQL: ``` # db/migrate/20140207133952_create_books.rb create_table :books do |t| t.string 'title' t.string 'tags', array: true t.integer 'ratings', array: true end add_index :...
Have you tried `MentorData.where("'apple' = ANY (os_usage)")`?
How can I query Rails ActiveRecord data stored in arrays
[ "", "sql", "ruby-on-rails", "ruby", "postgresql", "activerecord", "" ]
I have a table with 2 column like this: ``` city_name car_name Gurgaon Alto Gurgaon Mercedez Benz Gurgaon Swift Dzire New Delhi Alto New Delhi Etios New Delhi Mercedez Benz New Delhi Swift Dzire ``` I made this by running a query using `group by` tag, but my task...
This should be done in a front end / reporting tool and not using sql. If you have no option, try this ``` select case when sno=1 then city_name else '' end as city_name,car_name from ( select row_number() over (partition by city_name order by car_name) as sno, * from table ) as t ```
``` select city_name, (SELECT [car_name]+',' FROM [myTable] AS [t1] WHERE t1.[city_name] = t2.[city_name] FOR XML PATH('') ) AS cars FROM [MyTable] AS [t2] GROUP BY [t2].[city_name] ``` You can replace the , (or any other string you might use) with newline character in your display medium.
How to remove repetitive column entries?
[ "", "sql", "sql-server", "" ]
can someone help me to resolve this? ``` CREATE TABLE TT ( A NUMBER PRIMARY KEY, B VARCHAR2(5) ); insert into tt values (11,'A'); insert into tt values (12,'A'); insert into tt values (13,'B'); insert into tt values (14,'B'); insert into tt values (15,'C'); insert into tt values (16,'D'); insert into ...
You can find the candidates using a group by: ``` select a from tt where B in ( select B from tt group by b having count(*) >= 2); ```
This is easy enough with aggregations: ``` select a from tt where b in (select b from tt group by b having count(*) > 1); ``` As a note, you can avoid the use of aggregation, because Oracle provides the `rowid` pseudocolumn: ``` select a from tt where exists (select 1 from tt tt2 where t...
Any other option is there without using Oracle Analytical function
[ "", "sql", "oracle", "window-functions", "" ]
Is there a way to do the following query? It would save me having to go out of SQL to do post-processing of the query: ``` SELECT date, RANDOM('CA', 'DE', 'AZ') FROM table LIMIT 3 ``` And the result would be something like: ``` 2014-01-01,"CA" 2014-01-02,"CA" 2014-01-03,"DE" ``` Is there a way to do the `RANDOM` op...
Get your set of values to table/subquery with `UNION ALL`, sort by `RAND()` and return 1 value: **[SqlFiddleDemo](http://sqlfiddle.com/#!9/77fb8/4/0)** ``` SELECT id, (SELECT 'CA' AS 'col' UNION ALL SELECT 'DE' UNION ALL SELECT'CZ' ORDER BY RAND() LIMIT 1) AS Random FROM...
``` SELECT SUBSTRING_INDEX(SUBSTRING_INDEX('CA,DE,AZ',',',CEILING(RAND()*3)),',',-1); ``` or something like that
Select random value in SQL
[ "", "mysql", "sql", "" ]
Is there a way in SQL or PLSQL that makes sure that nothing is committed? Since, sometimes a function/procedure is called and the consequences are not known. For example, it can trigger an implicit commit. Is there a way to prevent that?
I am giving example in Oracle Database This is for the SQL statements DML. ``` SQL> set transaction read only; Transaction set. SQL> update t set t=14; update t set t=14 * ERROR at line 1: ORA-01456: may not perform insert/delete/update operation inside a READ ONLY transaction ``` This for calling procedure...
If you want to be sure that you won't modify anything, the "set transaction read only" is the right answer. Otherwise: if you are writing some code that calls other procedures wrote by other programmers and your main concern is that these other procedures might issue unwanted commits (or could in future be modified to...
Force rollback in case of an implicit commit
[ "", "sql", "oracle", "plsql", "commit", "rollback", "" ]
I'm currently running an instance of MS SQL Server 2014 (12.1.4100.1) on a dedicated machine I rent for $270/month with the following specs: * Intel Xeon E5-1660 processor (six physical 3.3ghz cores + hyperthreading + turbo->3.9ghz) * 64 GB registered DDR3 ECC memory * 240GB Intel SSD * 45000 GB of bandwidth transfe...
There is an alternative from Microsoft to Azure SQL DB: “Provision a SQL Server virtual machine in Azure” <https://azure.microsoft.com/en-us/documentation/articles/virtual-machines-provision-sql-server/> A detailed explanation of the differences between the two offerings: “Understanding Azure SQL Database and SQL Se...
(Disclaimer: I work for Microsoft, though not on Azure or SQL Server). "Azure SQL" isn't equivalent to "SQL Server" - and I personally wish that we did offer a kind of "hosted SQL Server" instead of Azure SQL. On the surface the two are the same: they're both relational database systems with the power of T-SQL to que...
Azure SQL Database vs. MS SQL Server on Dedicated Machine
[ "", "sql", "azure", "azure-sql-database", "sql-server-2014", "" ]
I'm trying to find rows which are present only in one table. Big table name (consists all rows) is `kwf_uploads`, small tables present in many names. My goal is find rows which exists in `kwf_uploads`, but not exists in other (this example are primary and foreigh keys in tables without relations). What I did in sql: ...
UNION (when used by itself, without ALL) is an "expensive" operation. There is an alternative, NOT EXISTS. This construct is a "semi join" and I suspect may be less expensive than a union approach. ``` SELECT id FROM kwf_uploads AS u WHERE NOT EXISTS (SELECT NULL FROM documents WHERE u.id = picture_id ) ...
**To fix your current error** Prefix Id column with proper resultset alias. In this case `kwf_uploads.id`. Because Id exists in both resultsets. **To get desired output** Add `Where foo.id is null`. This will fetch those ids which failed in join, those are the ids you want. ``` select kwf_uploads.id from ...
How to compare tables with many unions and join?
[ "", "mysql", "sql", "join", "union", "" ]
I'm dealing with the yelp dataset on `sqlite3`, and I have a schema as follows: ``` CREATE TABLE businesses (business_id text primary key, name text, full_address text, city text, stars decimal(1,1), ratings integer); ``` I run the following query: ``` select name, stars f...
In the [SQLite docs](https://www.sqlite.org/lang_select.html), it says: > If the SELECT statement is an aggregate query without a GROUP BY > clause, then each aggregate expression in the result-set is evaluated > once across the entire dataset. Each non-aggregate expression in the > result-set is evaluated once for an...
The problem is your `MIN()` function bring the smallest value for `stars`, but not the name match for that row. [**SQL Fiddle Demo**](http://sqlfiddle.com/#!9/44391/2) You can do a cross join ``` SELECT name FROM businesses b, ( SELECT min(stars) as MinValue FROM businesses WHERE ratings >= 400) ...
Why does nested query in SQLite return the wrong value?
[ "", "sql", "database", "sqlite", "" ]
This is table test ``` ID order_no film_type process line 100 RXQFW40-1 FW SL HL21 101 RXQFW46-1-1 EXFW EX HE15 103 RXQFW49-1 FW SL HL21 173 RXQFW49-1-1 EXFW EX HE15 107 RXQFW4E-1 FW ...
Well you can use a `WHERE EXISTS` like below by combining both the queries ``` Select distinct substring(order_no,1,7) from test t where process='EX' and EXISTS ( Select 1 from test where process='SL' and substring(t.order_no,1,7) = substring(order_no,1,7)); ```
A different aproach to `EXISTS` you can `JOIN` using the `substring` result. And is easier to read. And looks like the result is always the `SL.order_no` so no need apply another substring there. [**SQL Fiddle Demo**](http://sqlfiddle.com/#!6/0408a/4) ``` SELECT DISTINCT SL.order_no FROM test SL inner join test EX ...
Query table and compare with another query (if exist, show in result)
[ "", "sql", "sql-server", "" ]
I have table BIDS, which contains a lot of columns and rows but I only want to select a row which contains lowest BIDPRICE. ``` Select min(Cast(Bids.BidPrice as INT)), BidBidderName from bids BidBidderName ``` but it throws error > Column 'bids.BidBidderName' is invalid in the select list because it > is not contain...
You can use subquery: ``` Select BidPrice, BidBidderName from bids where Bids.BidPrice in (Select min(Cast(b.BidPrice as INT)) from bids b) ``` Or `INNER JOIN`: ``` Select b1.BidPrice, b1.BidBidderName from bids b1 inner join (select Min(BidPrice) BidPrice from @bids) as b2 on b.BidPrice = b2.BidPrice ```
Here is an option that will get just the row with the lowest price. ``` Select top 1 BidPrice , BidBidderName from bids order by Cast(BidPrice as INT) ```
How to select the record with minimum value from table?
[ "", "sql", "sql-server", "sql-server-2008", "sql-server-2012", "" ]
Say I have table 1 with: ``` stuff | sender_id | recipient_id ``` and I have table 2 with: ``` id | name ``` I want to return: `stuff | sender_name | recipient_name` or `stuff | sender_id | sender_name | recipient_id | recipient_name` Right now I'm looking at something like: `SELECT * FROM table1 INNER JOIN ...
A way is to use inner-selects like this: ``` SELECT stuff, sender_id , (SELECT name FROM table2 WHERE id = sender_id) AS sender_name , recipient_id , (SELECT name FROM table2 WHERE id = recipient_id) AS recipient_name FROM table1; ```
Solution with one reference to table2: ``` select t1.stuff , max(case when t1.sender_id = t2.id then t2.name end) as sender_name , max(case when t1.recipient_id = t2.id then t2.name end) as recipint_name from t1 join t2 on t2.id in (t1.sender_id, t1.recipient_id) group by t1.stuff; ``` It is a bit me...
Map 2 columns to 2 rows in 1 column?
[ "", "sql", "" ]
I have the following table ``` timestamp parameter value --------------------------------------------------- 2015-09-04 10:00:00.000 par01 1 2015-09-04 10:03:00.000 par02 2 2015-09-04 10:06:00.000 par03 3 2015-09-04 10:09:00.000 par04 ...
This will give you the result you are requesting: ``` DECLARE @t table(timestamp datetime, parameter char(5), value int) INSERT @t values ('2015-09-04 10:00:00.000','par01',1), ('2015-09-04 10:03:00.000','par02',2), ('2015-09-04 10:06:00.000','par03',3), ('2015-09-04 10:09:00.000','par04',4), ('2015-09-04 10:12:00.0...
try this: ``` SELECT MIN(timestamp) as timestamp, 'result' + cast(count(*) over(order by min(timestamp)) as varchar(10)) as parameter, AVG(value) as value FROM tbl GROUP BY CAST(timestamp as Date), DATEPART(Hour, timestamp), DATEPART(Minute, timestamp) / 15 ``` [see fiddle he...
Fastest way to calculate time periods weighted average in SQL Server
[ "", "sql", "sql-server", "" ]
I try to use an SQL query in Access but it doesn't work. Why? ``` SELECT * FROM table EXCEPT SELECT DISTINCT name FROM table; ``` I have a syntax error in FROM statement.
use HAVING COUNT(name) > 1 clause ``` SELECT * FROM Table1 WHERE [name] IN (SELECT name, Count(name) FROM Table1 GROUP BY name HAVING COUNT(name)>1) ```
MS Access does not support EXCEPT keyword. You can try using the LEFT JOIN like this: ``` select t1.* from table t1 left join table t2 on t1.name = t2.name ``` **EDIT:** If you want to find the duplicates in your table then you can try this: ``` SELECT name, COUNT(*) FROM table GROUP BY name HAVING COUNT(*) > 1 `...
How to find duplicates in a table using Access SQL?
[ "", "sql", "ms-access", "" ]
I have some duplicate values in a table and I'm trying to use `Row_Number` to filter them out. I want to order the rows using `datediff` and order the results based on the closest value to zero but I'm struggling to account for negative values. Below is a sample of the data and my current `Row_Number` field (`rn`) col...
You're close. Just add [`ABS()`](https://msdn.microsoft.com/en-US/library/ms189800(v=sql.120).aspx) to calculate absolute values of the differences: ``` ROW_NUMBER () OVER ( PARTITION BY PersonID ORDER BY abs(datediff(dd, dischargedate, surveydate)) asc ) AS rn ```
You could use [`abs`](https://msdn.microsoft.com/en-us/library/ms189800.aspx) to get the distance from zero: ``` select PersonID, SurveyDate, DischargeDate, datediff(dd,dischargedate,surveydate) days, ROW_NUMBER () over (partition by PersonID order by abs(datediff(dd,dischargedate,surveydate)) asc) as rn from Tabl...
SQL Server order by closest value to zero
[ "", "sql", "sql-server", "select", "sql-order-by", "row-number", "" ]
As the title says the query needs to combine multiple select queries. The question is as follows: **Display the total number of employees, and of that total the number of employees hired in 1995,1996,1997,1998.** My query: ``` select (select count(*) from employees) as "Total", (select count(*) from employees...
Assuming the years are really what you want, the problem with your query is that you are selecting from `employees`, so you get a row for each one. You could use: ``` select (select count(*) from employees) as "Total", (select count(*) from employees where hire_date between 'JAN-1-0095' and 'DEC-1-0095')as "199...
You can use conditional counting: ``` select count(*) as total_count, count(case when extract(year from hire_date) = 1995 then 1 end) as "1995", count(case when extract(year from hire_date) = 1996 then 1 end) as "1996", count(case when extract(year from hire_date) = 1997 then 1 end) as "1997", ...
Combining multiple SELECT queries in one
[ "", "sql", "oracle", "oracle11g", "" ]
I have to generate a report sales report for current day in which user will select start hour and end hour. It will be max 24 hours. Start hour will be 4:00 AM and max end hour can be next day 4:00 AM **The below query will return date-time and amount of sale** ``` select s.StartDate , CONVERT(DECIMAL(10,2),sum(O...
``` declare @starttime datetime = '2015-07-03 16:00:01' declare @endtime datetime = '2015-07-04 04:00:00' ;with reporttable as ( select s.StartDate , CONVERT(DECIMAL(10,2),sum(OrigionalSubTotal)/100.0) Amt from Sale s where s.StartDate BETWEEN @starttime and @endtime and s.IsSuspend...
I've approached this in two steps: 1. Get the range of `datetime` values using `MIN` and `MAX` on the data 2. Use these values to create the full range of dates and hours in a [**CTE**](https://technet.microsoft.com/en-us/library/ms190766%28v=sql.105%29.aspx?f=255&MSPPError=-2147217396) and join them back on to the da...
Show the total sale in Hourly basis
[ "", "sql", "sql-server", "sql-server-2008", "" ]
What I am trying to do is to create two timestamps a `StartDate` timestamp which will be `09/08/2015 00:00:00` and an `EndDate` time stamp which should be `09/08/2015 23:59:59` as easy as it is to achieve in MS SQL, I have not been able to find a `Make_Date` function or `Add_Days` function to get either of the timestam...
Use **TO\_DATE** to convert **string** into **DATE**. ``` SQL> alter session set nls_date_format='mm/dd/yyyy hh24:mi:ss'; Session altered. SQL> SELECT to_date('09/08/2015 00:00:00' ,'mm/dd/yyyy hh24:mi:ss') start_date, 2 to_date('09/08/2015 23:59:59' ,'mm/dd/yyyy hh24:mi:ss') end_date 3 FROM dual; STAR...
Rather than using fractional numbers `86399 / 86400` (which requires some working out when reviewing the code to see why you picked those magic numbers) to get the end date you can explicitly state the time periods using `INTERVALS` (which is easy to see at a glance what you are doing): [SQL Fiddle](http://sqlfiddle.c...
How to create day start and end date in PL SQL
[ "", "sql", "oracle", "plsql", "" ]
I am working on an Excel sheet based algorithm and trying to convert the logic in SQL. There is a need in my SQL logic where I need to create a temporary Table and I am stuck in referencing one aliased column in another aliased column of that table. It looks something like this- ``` INSERT INTO @tbl_CensusTable AS CST...
Try this: ``` INSERT INTO @tbl_CensusTable SELECT CS.gender, CS.salary, CS.birthday, CS.Age, (Col5 calculation) AS 'Column_5', ((Some calculation) * (Col5 calculation)) AS Column_6 From @tbl_tempTable as CS ``` This should work as well: ``` WITH CTE as ( SELECT CS.gender, CS.sal...
``` INSERT INTO @tbl_CensusTable (<good practice to list the columns here>) SELECT CS.gender, CS.salary, CS.birthday, CS.Age, CS.Column_5, <another calculation> * CS.Column_5 AS Column_6 FROM (SELECT *, <some calculation> AS Column_5 FROM @tbl_tempTable) AS CS ``` or ``` ;WITH CS AS ( SELECT *, <s...
how to Reference aliased column to another column of a temporary table in SQL?
[ "", "sql", "sql-server", "t-sql", "" ]
I have `Kpi_definition` table in which for particular event\_id there can be more than one `KPI_DEF_ID` present. For example for event\_id = `10250` there are two `KPI_DEF_ID`. I have to check first for the event\_id the `KPI_DEF_ID` is present or not and if it is not present then set the `STATUS` to `'N'`. In another ...
``` select decode(kpi_def_id,NULL,'N', case when instr(ini||curr||downtime||manual,'N',1) = 0 then status else 'N' end) from ex_6 ``` hi rahul, this query worked on my machine .Fullfilled your requirement.Please mark up the answer if it helps.
``` select case when decode(kpi_def_id,NULL,'N',col,0,'N') <> 'N' then status else 'N' end case from ( select kpi_def_id,instr(ini||curr||downtime||manual,'Y',1) col,ex_6.status status from ex_6 ) ``` This query works i have concatenated initial,downtime,current,manual column and with use of instr function finding wh...
Select case statement not working in oracle
[ "", "sql", "oracle", "view", "case-when", "" ]
I'm working in MS Access trying to iron out an SQL statement that works. On a form I have a combobox that displays a list of employees. I have a separate dialog form that allows the user to select multiple items in a listbox. Each item represents a certification. Each employee can have any number and combination of cer...
When you join tables, you basically query off a result set containing all the combinations of rows from those joined tables that your where clauses then operate off of. Since you are joining to the `Emp_Certs` table just once and linking only by Employee\_ID, you are getting a result set that looks like this (only show...
You should use `OR` operator in `WHERE` clause: ``` WHERE (((Employees.Active_Member) = Yes) AND ((Emp_Certs.Employee_ID) = [Employees].[Employee_ID]) AND ( Emp_Certs.Cert_ID = 1 OR Emp_Certs.Cert_ID = 4 ) ORDER BY Employees.Last_Name; ``` because of `Emp_Certs.Cert_ID = 1 and Emp_Ce...
SQL query with JOIN involving two criteria from same table
[ "", "sql", "ms-access", "join", "vba", "ms-access-2010", "" ]
I have a column in a SQL table I'm trying to do an order by on. The data needs to be in desc so it shows more recent years first. ``` Sample Data Expect Output ----------- ------------- older 2013 2012 2012 2013 2011 2011 older ...
You can use a `CASE` statement in the `ORDER BY` clause: ``` WITH tbl AS( SELECT 'older' AS date_col UNION ALL SELECT '2012' UNION ALL SELECT '2013' UNION ALL SELECT '2011' ) SELECT * FROM tbl ORDER BY CASE WHEN date_col NOT LIKE '%[^0-9]%' THEN 0 ELSE 1 END, date_col DESC ...
Can we not use the `ISNUMERIC()` function instead of `NOT LIKE` ``` DECLARE @test TABLE ( value varchar(10) ) INSERT INTO @test VALUES ('2010'), ('2011'), ('2012'), ('2013'), ('2014'), ('2015'), ('older') SELECT * From @test ORDER BY (CASE WHEN ISNUMERIC(value) = 1 THEN 0 ELSE 1 END),value DESC ```
SQL Order by DESC on alphanumeric field with numbers before words
[ "", "mysql", "sql", "sql-server", "select", "kentico", "" ]
``` select * from payments where amount = 0 order by id desc ``` I need to get the values which it has `0.5` part only.Could you tell me how to do that ? e.g. 12,12.5,12.6,14.5 results data set can be have : `12.5,14.5` values data only
Truncate amount to integer, subtract from original value and compare with 0.5 ``` SELECT * FROM payments WHERE amount - CAST(amount AS INT) = 0.5 ORDER BY id DESC ``` OR: ``` SELECT * FROM payments WHERE amount - FLOOR(amount) = 0.5 ORDER BY id DESC ``` Hacks way: ``` SELECT * FROM payments WHERE PARSENAME(...
you can find this way also ``` declare @temp table (val decimal(18,3)) insert into @temp values (0.5),(10.5),(20.8) select * from @temp where (val % 1) = 0.5 ```
Get the specified decimal part having data only from the sql query
[ "", "sql", "sql-server", "" ]
I have an Oracle table with the following data: ``` ID VALUE 10 A 10 B 10 C 20 A1 30 C1 30 D1 ``` I want to do a *group by* based on the ID column and print a new column with the sequence number within each group. The output would look like this: ...
You need [ROW\_NUMBER](http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions137.htm) ``` SELECT ID, VALUE, row_number() OVER (PARTITION BY ID ORDER BY value) GROUPSEQ FROM myTable ```
You can try this:- ``` SELECT ID, VALUE, ROW_NUMBER() OVER (PARTITION BY ID ORDER BY VALUE) "GROUPSEQ" FROM YOUR_TABLE; ```
Add a sequence number for each element in a group using an Oracle SQL query
[ "", "sql", "oracle", "oracle11g", "" ]
I have table `friends` below. ``` ----------------------------- | id | user_id | friends_id | ----------------------------- | 1 | 1 | 2 | ----------------------------- | 2 | 1 | 3 | ----------------------------- | 3 | 1 | 4 | ----------------------------- | 4 | 2 ...
Do a `GROUP BY` to count number of friends. Use a `CASE` to return 'Many' if more than 1 friend, or the friend\_id if only one (need to `CAST` to a character type, compatible with 'Many'.) ``` select user_id, case when count(friends_id) > 1 then 'Many' else cast(min(friends_id) as varchar(11)) end as fr...
I update the query and include [**SQL FIDDLE DEMO**](http://sqlfiddle.com/#!6/e2406/8) ``` WITH fCount as ( SELECT user_id, min(friends_id) friends_id, count(friends_id) nFriend FROM friends GROUP BY user_id ) select user_id, CASE WHEN nFriend > 1 THEN 'many' ...
condition in returning number of column
[ "", "sql", "sql-server", "" ]
I have this SQL statement: ``` SELECT * FROM `table` WHERE type = 3 OR type = 5 OR type = 4 and table.deleted = 1; ``` I've read that I can use parenthesis to accomplish this but I was wondering if then this would be valid: ``` SELECT * FROM `table` WHERE (type = 3 OR type = 5 OR type = 4) and table.deleted = 1; ```...
Both of these would be valid, but [since `AND` has higher precedence than `OR`](https://stackoverflow.com/q/1241142/335858), they would mean different things: * Your first parenthesized query would pick deleted rows with types 3, 4, 5 * Your second parenthesized query would select all rows with types 3, 5, in addition...
What you need is `IN` operator like ``` SELECT * FROM `table` WHERE type IN ( 3, 5, 4) and deleted = 1; ```
How can I combine ANDs and ORs in my SQL statement
[ "", "mysql", "sql", "" ]
I'm trying to start with SQLite in android but I have some problems.. I took the code from a tutorial which was written in 2012, but it's not working for me now and shows me this error: > E/SQLiteLog﹕ (1) near "Table": syntax error The problem is with creating/opening the Database. ``` package db.com.example.kids1...
``` private final String TABLE_NAME = "Table" ``` You can't create a table named `Table`, because it's a reserved keyword. You better create a table named `MyTable` (or `_Table` or better give a more talkative name, such as `Persons` - note the **s** for plurals). So: ``` private final String TABLE_NAME = "MyTable...
Try `VARCHAR(100)` and remove the trailing `;`
E/SQLiteLog﹕ (1) near "Table": syntax error
[ "", "android", "sql", "sqlite", "syntax-error", "" ]
I am trying to convert `Aug/14/2014` to `2014-08-14` but can't get it to working and throws below error. Could someone please suggest. ``` Update test set UserDATE =convert(nvarchar(10), cast(UserDATE as datetime),105) ``` > Error: The conversion of a nvarchar data type to a datetime data type > resulted in an o...
SQL Server doesn't understand that date format, so the `cast` will fail to parse it. Convert it to the format `'Aug 14 2014'` which you can use format 109 to parse. The format `yyyy-mm-dd` has the code 120. ``` update test set UserDATE = convert( nvarchar(10), convert(datetime, replace(UserDATE, '/', ' '...
Try replacing the slashing with spaces and using style 100 for the conversion to date: ``` Update test set UserDATE = convert(nvarchar(10), convert(date, replace(UserDate, '/', ' '), 100), 105) ``` However, if you are going to store dates as strings -- which I don't recommend -- then use an ISO standard format: ...
Convert Date time format in SQL
[ "", "sql", "sql-server-2008", "" ]
Can anyone help me un derstand the syntax of using AND like 4 times. I have this piece of code ``` WHERE (ListPrice >= 400) and (ListPrice <= 800) AND (Color = 'Red') OR (Color = 'Black') ``` Once evaluated it gives many other columns which do not have the color red or black. help please
Perhaps you should change it to ``` WHERE ((ListPrice >= 400) AND (ListPrice <= 800)) AND (Color = 'Red' OR Color = 'Black') ``` Please correct me if i'm wrong.
``` WHERE (ListPrice BETWEEN 400 and 800) AND (Color in ('Red','Black')) ```
SQL multiple AND and OR
[ "", "sql", "" ]
I have a result set of several columns that may or may or may not have nulls. I want the first non null result that is greater than 1, what's the best way to add this secondary condition when coalescing my columns? e.g. ``` result: col1 col2 col3 1 null 2 null 1 3 null null 4 ``` returns 2 3 and 4
lad2025's answer is correct, and you have to have an if for each column. But, since you have to have those if functions anyway, you might as well do ``` SELECT IF(col1>1, col1, if(col2>1, col2, if (col3>1, col3, null))) ``` or similarly ``` SELECT CASE WHEN col1>1 THEN col1 WHEN col2>1 THEN col2 WHEN c...
``` SELECT COALESCE(IF(col1>1,col1, NULL), IF(col2>1, col2, NULL), IF(col3>1, col3, NULL)) FROM tab ```
MySQL coalesce with extra condition
[ "", "mysql", "sql", "" ]
I have an SQL question I've been struggling with and hope someone can help. I have the following data: ``` TEAM | USERID | STEP1 | STEP2 | STEP3 | STEP4 | STEP5 001 | 000001 | Y | Y | N | N | Y 001 | 000002 | Y | N | N | Y | Y 002 | 000003 | N | Y | Y | N | ...
``` select team from table group by team having sum(case step1 when 'N' then 0 else 1 end) = 0 or sum(case step2 when 'N' then 0 else 1 end) = 0 or sum(case step3 when 'N' then 0 else 1 end) = 0 or sum(case step4 when 'N' then 0 else 1 end) = 0 or sum(case step5 when 'N' then 0 else 1 end) = 0 ``` Here's a fid...
I went the other way, but Blorgbeard was much faster than me. ``` select TEAM from TEAMS group by TEAM having count(case STEP1 when 'Y' then 1 end) = 0 or count(case STEP2 when 'Y' then 1 end) = 0 or count(case STEP3 when 'Y' then 1 end) = 0 or count(case STEP4 when 'Y' then 1 end) = 0 or count(case STEP5 when...
SQL - Select rows where all values in a column are the same
[ "", "sql", "" ]
I am using the following query to return the length of the longest value for Field1: ``` SELECT MAX(LEN(Field1)) FROM Table1 ``` How can I modify my query to return second largest length for Field1?
In the inner query, you can select the maximum length of the column and eliminate it in the outer query and do a `max` so you get the second largest length in that column. ``` select max(val) as secondlargest from t join ( SELECT max(len(val)) as lf1 FROM t ) x on len(t.val) < x.lf1 ``` If you need all the values wit...
SQL Server 2012+ supports `OFFSET/FETCH`: ``` select len(f1) from table1 group by len(f1) order by len(f1) desc offset 1 fetch first 1 row only; ``` In earlier versions there are various methods. Here is one: ``` with ml as ( select len(f1) as lenf from table1 group by len(f1) ) select max(len...
Selecting second largest length of a field in a table
[ "", "sql", "sql-server", "" ]
I have one table `ABC`. I am using queries ``` select count(*) from ABC where COLA=123; //output is 3 ``` `select count(*) from ABC WHERE COLA=321; //output is 6` I want both output combined like ``` | someColumnName | | 3 | | 6 | ``` Is there any way to frame query so that I can achieve ...
Use `UNION` between your two queries: ``` select count(*) as someColumnName from ABC where COLA=123 union select count(*) from ABC WHERE COLA=321; ```
use a group by and where clause. ``` SELECT count(*) as SomeColumnName FROM ABC WHERE COLA in (123,321) GROUP BY ColA ```
How to get combined output from two or more than two queries?
[ "", "sql", "database", "oracle", "" ]
I have a SQL table with one float column populated with values like these: ``` 1.4313 3.35 2.55467 6.22456 3.325 ``` I need to select rows containing only values with more than 4 decimals. In this case, the select must return: ``` 2.55467 6.22456 ``` Ideas? Thanks! This is what I have tried so far ``` s...
``` DECLARE @tbl TABLE (val float) INSERT INTO @tbl SELECT 1234.567 INSERT INTO @tbl SELECT 1234.5678 INSERT INTO @tbl SELECT -1234.5678 INSERT INTO @tbl SELECT 1234.56789 SELECT * from @tbl where (((val*10000) - CONVERT(INT,(val*10000))) <> 0) ```
Why cant we make it simple by this query:- ``` SELECT * FROM table WHERE val LIKE '%.____%' ``` This selects what we want
Select numbers with more than 4 decimal places
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I am trying to join 2 tables at once, the problem is that im getting an empty set with the following query. ``` select a.id, a.name, d.name, b.id, c.id from a inner join b on a.id = b.a_id inner join c on a.id = c.a_id inner join d on a.d_id = d.id ``` My guess is that this is happening because both B and C tables no...
From what you say, if B and C not always have matches, you need to left join those (and those only). ``` SELECT a.id, a.name, d.name, b.id, c.id FROM a LEFT JOIN b on (a.id = b.a_id) LEFT JOIN c on (a.id = c.a_id) JOIN d on (a.d_id = d.id); ``` Here A and D must always match, while matching records from B...
Use LEFT JOIN: ``` select a.id, a.name, d.name, b.id, c.id from a inner join b on a.id = b.a_id LEFT join c on a.id = c.a_id LEFT join d on a.d_id = d.id ```
Mysql joining 2 tables in same query. Inner join or Left join?
[ "", "mysql", "sql", "" ]
> I want to Join two tables based on id or default id. I've two tables thats storred all countries in different languages: **country:** ``` CREATE TABLE `country` ( `ctry_id` smallint(7) unsigned NOT NULL AUTO_INCREMENT, `ctry_iso` varchar(2) DEFAULT NULL, PRIMARY KEY (`ctry_id`) ); ``` **country\_lang:** ``...
Maybe the following is more what you are looking for? ``` SELECT c.ctry_id, cl.ctryl_name,cl.ctryl_lang_id, c.ctry_iso, c.ctry_iso3, c.ctry_flag, c.ctry_phone_code FROM country c LEFT JOIN country_lang cl on cl.ctryl_ctry_id = CASE WHEN EXISTS(SELECT 1 FROM country_lang WHERE ctryl_ctry_id=ctry_id) TH...
You can try this: ``` SELECT c.ctry_id, cl.ctryl_name,cl.ctryl_lang_id, c.ctry_iso, c.ctry_iso3, c.ctry_flag, c.ctry_phone_code FROM country c LEFT JOIN country_lang cl on cl.ctryl_ctry_id = c.ctry_id where (cl.ctryl_lang_id=129 AND cl.ctryl_lang_id=1) ORDER BY c.ctry_iso ASC ```
MYSQL: How to JOIN tables based on id if not found any record then by default value
[ "", "mysql", "sql", "join", "" ]
I have rarely use SQL, however for this task it may be the most suitable. I am looking to create a query that is able to detect the first occurrence of an incident for each subject. **Record:** ``` ------------------------------ personID | date | incident ------------------------------ 1 20150901 F1 2...
Using MIN should work for this: ``` select personId,incident,MIN(convert(date,date)) as date from [table] group by personId,incident ```
You can use `row_number` function to get the desired result. [Fiddle with sample data](http://www.sqlfiddle.com/#!3/a2d86/1) ``` select personid, date, incident from ( select *, row_number() over(partition by personid, incident order by date) as rn from tablename ) x where x.rn = 1; ```
SQL: First Occuerence and with value
[ "", "sql", "sql-server-2008", "" ]
I have following values in a column of table. there are two columns in table. The other column is having distinct dates in descending order. ``` 3 4 3 21 4 4 -1 3 21 -1 4 4 8 3 3 -1 21 -1 4 ``` The graph will be [![enter image description here](https://i.stack.imgur.com/LSL4X.jpg)](https://i.stack.imgur.com/LSL4X.jpg...
[SQL Fiddle](http://sqlfiddle.com/#!4/b92dc/1) **Oracle 11g R2 Schema Setup**: ``` CREATE TABLE TEST ( datetime, value ) AS SELECT DATE '2015-01-01', 3 FROM DUAL UNION ALL SELECT DATE '2015-01-02', 4 FROM DUAL UNION ALL SELECT DATE '2015-01-03', 3 FROM DUAL UNION ALL SELECT DATE '2015-01-04', 21 FROM DUAL U...
Just for completeness the row pattern matching example: ``` WITH source_data(datetime, value) AS ( SELECT DATE '2015-01-01', 3 FROM DUAL UNION ALL SELECT DATE '2015-01-02', 4 FROM DUAL UNION ALL SELECT DATE '2015-01-03', 3 FROM DUAL UNION ALL SELECT DATE '2015-01-04', 21 FROM DUAL UNION ALL SELECT ...
Oracle: Identifying peak values in a time series
[ "", "sql", "oracle", "" ]
At the first excuse me for my bad english. I have two tables: 1. master table: ``` | product id | pr_name | remain_Qty | +--------------+------------------+-------------------+ | 1 | x | 13 | | 2 | y | 18 ...
More of a clarification than a direct SQL answer. But what it LOOKS like they may be wanting is based on an inventory being depleted to fill orders from the known available quantity, but even that falls short as the may be missing a second qty of 3 on 2010-01-03 for product 1... which if looking at just ID=1 from his s...
Here a working query for pr\_id=1 , I used MySql: ``` select final.pr_date, final.pr_id, count(t_qty) as qty, final.price from (select * FROM (select q.pr_date, q.pr_id, 1 as t_qty, q.price , @t := @t + t_qty total FROM( SELECT d.pr_date, d.pr_id, 1 as t_qty, d.price FROM detail_table d JOIN generator_4k i ON...
Sql query for special record
[ "", "sql", "t-sql", "" ]
I have an original table named 'student' like this: ``` idstudent studentname studentclass 101 adam A 102 brian NULL 103 charlie C 104 danny D ``` Then, I have a temporary table name 'student\_temp' like this: ``` idstudent studentname ...
Try this: ``` UPDATE stu SET [studentname] = CASE WHEN tmp.[studentname] IS NOT NULL THEN tmp.[studentname] ELSE stu.studentname END , [studentclass] = CASE WHEN tmp.[studentclass] IS NOT NULL THEN tmp.[studentclass] ELSE stu.studentclass END FROM [student] stu INNER JOIN [student_temp] tmp ON stu.[idstudent]...
Use a condition in your `WHERE` clause to ignore `NULL` values ``` UPDATE stu SET [studentname] = tmp.[studentname] , [studentclass] = tmp.[studentclass] FROM [StudentDatabase].[dbo].[student] stu INNER JOIN [StudentDatabase].[dbo].[student_temp] tmp ON stu.[idstudent] = tmp.[idstudent] WHERE tmp.[studentname...
Updating table without replacing values that already exist in the original table with null values from the temporary table
[ "", "sql", "sql-server", "t-sql", "sql-server-2008-r2", "" ]
I need add a where clause only if a condition is respected, for example : ``` SELECT * FROM car Where <a condition> and ( if (car.brand = 'Renault') then car.color = 'red') ``` In my example : if the brand is renault i want only red cars and I want other car only if there isn't renault Is it possible to write somet...
You can't use an `if` in a `where` clause (SQL doesn't even know `if`). To achieve what you want you need to use something like: ``` where ... and (car.brand = 'Renault' and car.color = 'red' or car.brand <> 'Renault') ``` This disjunction says *"if the brand is Renault, then the color needs to be red, for other bran...
Simple logic below. You might want to write a truth table for any query like this if you are not sure. ``` SELECT * FROM car WHERE <a condition> AND ((car.brand= 'Renault' and car.color = 'red') OR car.brand != 'Renault') ```
If statement in clause where
[ "", "sql", "oracle", "" ]
I have the following table: ``` +----+----------+ | id | feature | +----+----------+ | 1 | 10 | | 1 | 20 | | 2 | 20 | | 3 | 40 | | 4 | 50 | | 5 | 60 | +----+----------+ ``` And I'd like to have the id's that have both features 10 and 20. So, not just the results that have 10...
The easiest way would be to `GROUP BY` the `id` and use `HAVING`: ``` SELECT id FROM table_name WHERE feature IN (10,20) GROUP BY id HAVING COUNT(distinct feature) = 2 ```
Another way to select the id that have features 10 and 20 you can do so ``` select id from table1 group by id having sum(feature = 10) and sum(feature = 20) ``` [`DEMO`](http://sqlfiddle.com/#!9/dbf10b/1)
SQL select rows with filters
[ "", "mysql", "sql", "" ]
I have two tables that can be joined using one field: ``` Table_1: emp_id emp_name department ------ -------- ---------- 1 Adam Accounting 2 Peter Engineering 3 Bruce Engineering Table_2: emp_id emp_salary ------ ---------- 1 1000 3 ...
So easy, just remove table\_2 from sub-query: ``` select * from table_2 where not exists (select 1 from table_1 where table_1.emp_id = table_2.emp_id); ```
Try: ``` select * from table_2 where emp_id not in (select emp_id from table_1) ```
Selecting rows that don't exist when joining two tables
[ "", "sql", "oracle", "join", "oracle11g", "" ]
Code ``` CREATE TABLE #Temp (ValA varchar(10) NULL, FK_ID int) INSERT INTO #Temp SELECT 'A',1 UNION ALL SELECT 'A',1 UNION ALL SELECT 'A',1 UNION ALL SELECT 'A',2 UNION ALL SELECT 'B',1 UNION ALL SELECT 'B',2 UNION ALL SELECT 'C',1 UNION ALL SELECT 'C',1 UNION ALL SELECT 'C',1 SELECT ValA , FK_ID , CASE WHEN COUNT(*...
If you don't have `NULL` Value in `FK_ID` ``` SELECT ValA , FK_ID , CASE WHEN COUNT(*) OVER (PARTITION BY ValA) > dense_rank() OVER (PARTITION BY ValA ORDER BY FK_ID ASC) + dense_rank() OVER (PARTITION BY ValA ORDER BY FK_ID DESC) -1 -- Get Distinct FK_ID Count THEN 1 ELSE 0 END IsMultiple ...
Not very elegant but works: ``` select t.*, case when tex.ValA is null then 0 else 1 end IsMultiple from #Temp t left join ( select ValA from #Temp group by ValA, FK_ID having count(*) > 1 ) tex on t.ValA = tex.ValA ``` Here in inner query we se...
T-SQL | Find multiples (with a twist?!)
[ "", "sql", "sql-server", "t-sql", "sql-server-2012", "" ]