Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I'm on oracle 11g and I am stuck on this problem. My table structure is as below ``` ╔═══════╦══════╦════════╗ ║ tm_id ║ flag ║ countr ║ ╠═══════╬══════╬════════╣ ║ 1 ║ 0 ║ null ║ ║ 2 ║ 0 ║ null ║ ║ 3 ║ 1 ║ null ║ ║ 4 ║ 0 ║ null ║ ╚═══════╩══════╩════════╝ ``` I want to update all...
[SQL Fiddle](http://sqlfiddle.com/#!4/b2beb1/1) **Oracle 11g R2 Schema Setup**: ``` CREATE TABLE test ( tm_id, flag, countr ) AS SELECT 1,0, CAST( NULL AS NUMBER ) FROM DUAL UNION ALL SELECT 2,0, CAST( NULL AS NUMBER ) FROM DUAL UNION ALL SELECT 3,1, CAST( NULL AS NUMBER ) FROM DUAL UNION ALL SELECT 4,0, CA...
You want to use a subquery in the `update`: ``` update calendar t set countr = (select count(*) from calendar t2 where t2.tm_id <= t.tm_id and t2.flag = 0 ); ``` If your table is large, you might find that `merge` is more efficient.
Update a column sequentially based on condition
[ "", "sql", "oracle", "oracle11g", "" ]
I would like to update a part of string in a particular column of my database. I have cm2 in the particular column of my database and would like to update it to cm2. My sql query to find the cm2 is: ``` SELECT * FROM `question_table` WHERE `option` LIKE '%cm2%' ``` To update I want to try is this: ``` Update ...
The reason you get an error is probably since `option` is a reserved word in MySql. to escape reserved words in MySql use this char **`**: ``` UPDATE question_table SET `option` = Replace(`option`, 'cm2','cm<sup>2</sup>') WHERE `option` LIKE '%cm2%' ``` [Here is a list of reserved words in MySql](http://dev.mysql.c...
Your guess looks almost correct. I just tried your code in SQL Server and it works a treat. ``` UPDATE table SET field = Replace(field, 'string to replace','replace with this') WHERE field LIKE '%filteredby%' ```
Update part of a string in SQL
[ "", "mysql", "sql", "sql-update", "" ]
Lets say emp is hired on 10 Apr 15 and is transferred on 30 Apr 15 and again promoted on 10 june 15. So from this history i need the very first and last (recent record) from the emp\_data. action\_date are the dates mentioned above. So i need 10 Apr and 10 june as a output for my query. Action refereed as hire, transfe...
I think you have to modify your query to something like the following: ``` select empid, action, action_dt from ps_job where action_dt in (select min(action_dt) from ps_job where empid='88888' UNION ALL select max(action_dt) ...
[SQL Fiddle](http://sqlfiddle.com/#!4/ed329/1) **Oracle 11g R2 Schema Setup**: ``` CREATE TABLE ps_job ( empid, action, action_dt ) AS SELECT 88888, 'Join', DATE '2015-04-10' FROM DUAL UNION ALL SELECT 88888, 'Transfer', DATE '2015-04-30' FROM DUAL UNION ALL SELECT 88888, 'Promote', DATE '2015-06-10' F...
How to get the first and last dates/records from the employee history table
[ "", "sql", "oracle", "" ]
I have a PostgreSQL database, with only `SELECT` permissions. In this DB there are two tables with the same structure (the same columns). I need to write several query in each table and join the results. There is a way for writing a query like this one? ``` SELECT field1, field2, field3 FROM table1 AND tab...
`UNION ALL` ``` SELECT field1, field2, field3 FROM table1 WHERE condition UNION ALL SELECT field1, field2, field3 FROM table2 WHERE condition; ``` Or to simplify your WHERE condition ``` SELECT * FROM ( SELECT field1, field2, field3 FROM table1 UNION ALL SELECT field1, field2, field3 FROM table2 ) ...
You can use Union: ``` SELECT field1, field2, field3 FROM table1 UNION SELECT field1, field2, field3 FROM table2 ```
How to create a SELECT query FROM "TABLE1 AND TABLE2"
[ "", "sql", "sql-server", "postgresql", "sql-server-2008", "join", "" ]
I have next table: ``` COLUMN_NAME DATA_TYPE PK NULLABLE inc_id bigint YES NO dt_cr timestamp NO NO email varchar(255) NO YES ``` `email` column is not unique, so I should use `GROUP BY email`. **Question**: How can I get from this table minimal date, next row after minima...
This query uses `WITH` construction that works similar to sub-queries. Investigate this query with `EXPLAIN` before use in production because it may be slow on big tables: ``` WITH orders AS ( SELECT email , first_value(dt_cr) OVER wnd1 AS min_date , nth_value(dt_cr, 2) OVER wnd1 AS seco...
Try with `row_number` function. Within whole table: ``` select * from(select *, row_number() over(order by dt_cr) rn from tableName)t where rn <= 2 ``` Or within `email`: ``` select * from(select *, row_number() over(partition by email order by dt_cr) rn from tableName)t where rn <= 2 ```
How to get second row in PostgreSQL?
[ "", "sql", "postgresql", "" ]
I need to convert **2014-11-18T14:08:43+00:00** which is in varchar in my sql developer to date format in order to filter a few entries. **I tried** `to_date(LAST_UPDATE_DATE,'YYYY-MM-DD')` **but it gives an error** > ORA-01830: date format picture ends before converting entire input > string. Kindly help..
Just in case you didn't mean to put up sql server but instead you need to use oracle (seeing as you are using to\_date and you are getting an ora exception) I added a quick datetime conversion for date and timestamp (no milliseconds) for your date format: ``` SELECT to_Date(concat (substr ...
You could try this; ``` Select CAST ('2014-11-18T14:08:43+00:00' as date) ``` The assumption is you are in SQL Server 2012
Converting string to date in sql
[ "", "sql", "oracle", "date", "type-conversion", "timestamp-with-timezone", "" ]
I want to find any character occurs between 4 and 10 times, I used `REGEXP_LIKE` but it's valid just for one character 'a' , I want to find for all alphabet: ``` SELECT regex_test_name FROM regex_test WHERE REGEXP_LIKE(regex_test_name, 'a{4,10}') ```
``` SELECT regex_test_name FROM regex_test WHERE REGEXP_LIKE(regex_test_name, '([[:alpha:]])\1{3,9}') ``` Inspired by [dnoeth's answer](https://stackoverflow.com/a/30845819/4607488), but since it catches the first character, specifying 3-9 subsequent repeats means 4-10 successive occurences in total.
Use `[[:alpha:]]` ``` REGEXP_LIKE(regex_test_name, '[[:alpha:]]{4,10}'); ```
Find any character occur more than 4 times
[ "", "sql", "regex", "oracle", "" ]
``` DECLARE @Date DATE = '2/28/2014' ``` I need to test whether the DAY in the DATE above is the LAST day of the month and it should work for all months in the year. If it's true, then I need to return a true, if not, then false. E.g. ``` SET @Date = '2/27/2014' ``` This should return FALSE. ``` SET @Date = '12/3...
An easy way that works in almost any version of SQL Server is: ``` select (case when month(@date) <> month(dateadd(day, 1, @date)) then 'true' else 'false' end) ``` That is, add a day and see if you are in the same month. This works for leap years, and Dec 31 and so on.
This will return 1 if its the last day of the month, and 0 otherwise ``` DATEDIFF(month,@date,@date+1) ```
How do I check whether the input date's DAY is the last day of the given month in SQL?
[ "", "sql", "sql-server", "datepart", "" ]
I have this ms access query: ``` SELECT t1.sb, suchbegriff2, menge FROM (SELECT artnr & '/' & [lfdnr-kal] AS sb, left(suchbegriff,7) & val(right(suchbegriff,4)) AS suchbegriff2 FROM kvks WHERE suchbegriff like '*/*') AS t1 INNER JOIN (SELECT artnr & '/' & [lfdnr-kal] AS sb, [...
You do have a complicated mess with those calculated fields. Why not join more directly? This query below leaves one `'/'` unaccounted for, but should tell you what I'm thinking of. ``` SELECT t1.sb, left(st1.uchbegriff,7) & val(right(t1.suchbegriff,4)) AS suchbegriff2, t1.menge FROM kvks AS t1 INNE...
For the inner join, you can try to use a saved query (or temp table) instead of writing the query at run time. So, I would first try to abstract this query ``` SELECT artnr & '/' & [lfdnr-kal] AS sb, [artnr-hz] & '/' & val(lfdnr) AS hz, menge FROM konf WHERE [artnr- ...
ms access query very slow
[ "", "sql", "ms-access", "join", "" ]
I need to retrieve data from MySQL from one day, but I don't know the interval between two rows (there may be 4 rows from one day and a gap of a week for example). Let's say I have: *(following isn't code)* ``` 3 rows where date = 2015-06-15 1 row where date = 2015-06-09 4 rows where date = 2015-06-05 ``` I want to ...
If I understand correctly, you want to receive one days worth of rows before a given date. I think that would be: ``` SELECT t.* FROM table t WHERE date = (SELECT MAX(t2.date) FROM table t2 WHERE t2.`date` < '2015-06-07') ```
I think you want something like this: ``` select * from table where date = (select max(date) from table where date < '2015-06-14') ```
Select before specific date from one day only
[ "", "mysql", "sql", "date", "" ]
I am using SQLite in an iOS application and I am using FMDB as a wrapper. This is my database schema : ``` CREATE TABLE Offer (code TEXT PRIMARY KEY NOT NULL, name TEXT); CREATE TABLE OffreMarket (codeOffer TEXT NOT NULL, codeMarket TEXT NOT NULL, FOREIGN KEY(codeOffer) REFERENCES Offer(code), FOREIGN KEY(codeMarket)...
What I can suggest is: * Refine your SQL statement. Instead of 2 loops, you can simply change your statement into "`SELECT * FROM OffreMarket WHERE codeOffer IN (SELECT code FROM Offer)`". If you want to use column "`name`" in table "`Offer`", you can join two tables "`codeOffer`" and "`Offer`". The rule of thumb here...
In this case you can get the results with just one query: ``` select * from Offer left outer join OffreMarket OM on (OM.codeOffer = Offer.code) ```
Fetching complex data using FMDB
[ "", "sql", "objective-c", "sqlite", "fmdb", "" ]
I have two tables : 'pc' and 'results'. the table 'results' contains so many results of every pc. I need to create view that contains all pc columns and the last result of every pc. I've tried this but it didn't work. ``` select * from pc,resultat where pc.code_pc=result.code_pc order by code_resultat DESC limit 3 ```...
I think what you are looking for is something like this: ``` Select p.*,r.* from pc p inner join Results r on p.ID_pc = r.ID_pc Where r.Code_reslt = (Select MAX(code_rslt) from results where ID_pc = p.ID_PC) ```
You could do this: ``` select r.id_pc, p.name, p.x, p.y, r.code_rslt, r.parametre, r.value, r.date from ( -- Get the max result per PC select max(code_rslt) as code_rslt from result group by id_pc ) maxPerId inner join result r on maxPerId.code_rslt = r.code_rslt -- join maxPerId onto result table, to ...
SQL: Create view using multiple tables and a cursor
[ "", "sql", "view", "" ]
How to get only last record ``` strConnStr = "Provider=SQLNCLI11;..." Set cn = server.CreateObject("ADODB.Connection") cn.Open strConnStr strSQL = "SELECT DISTINCT year1 FROM cars WHERE year1 > 1900 ORDER BY year1;" Set rs = Server.CreateObject("ADODB.Recordset") Set rs.ActiveConnection = cn rs.Open strSQ...
Based on the update: ``` Set rs.ActiveConnection = cn rs.Open strSQL YearList = rs.GetRows() MaxYear = YearList(0,UBound(YearList)) cn.Close ``` --- Older answer: If you're insistent on not changing the SQL (and so forcing the server to do more work on data that you're just going to throw away), then yo...
You can use the TOP keyword to get the latest record like this: ``` SELECT TOP 1 year1 FROM cars WHERE year1 > 1900 group by year1 ORDER BY year1 desc; ```
SQLSERVER get last record from recordset
[ "", "sql", "sql-server", "" ]
``` =Switch(Fields!CompnyID.Value=5, "company 1" "dsSalesManagement", Fields!CompnyID.Value=6, "company 2" "dsSalesManagement" ) ``` Trying to use switch statement to display two different results in my report. Was maybe looking for syntax correction or is there a way to use an else if statement? Problem is I want thi...
It seems that you have more than one datasource in your report so you have to specify the correct scope of your aggregate function. For example: ``` =Switch( First(Fields!CompnyID.Value, "dsSalesManagement") = 5, "company 1", First(Fields!CompnyID.Value, "dsSalesManagement") = 6, "company 2" ) ```
You want to use an IIF (immediate if) statement. The MSDN page is [here](https://msdn.microsoft.com/en-us/library/ms157328.aspx)
Trying to use Switch statement in SSRS
[ "", "sql", "reporting-services", "ssrs-2012", "" ]
Sorry for the subject as it is not very definientia. I have 2 tables, one stores Person Data and one stores Subject data along with the person interested in. Two tables looks like below **Person** ``` Id Name 1 Imad 2 Sumeet 3 Suresh 4 Navin ``` **Subjects** ``` Id PId Subject 1 1 DC 2 1 DS 3 3 ...
Simply order the data and get top most one record with ties(this means if some students have equal counts they both will come in result): ``` select top 1 with ties p.Id, p.Name from Subjects s join Person p on s.PId = p.Id group by p.Id, p.Name, order by count(*) desc ```
You can try this : ``` ;With c as ( select Pid, count(Id) as 'Total' from subject group by Pid ) select * from Person join c on c.Pid=Person.Id where c.total>1 ```
Getting Person having interests in more number of subjects - Sql Server
[ "", "sql", "sql-server", "" ]
Here is the Query: ``` SELECT DECODE(AVSR.INFORMATIONTYPE,'NULL','UNKNOWN','5','Infectious Agent Transmission Issue','4','Environmental Issue','3','Withdrawal Period Issue','2','Lack OF Expected Efficacy','1','Safety Issue') Infotype, COUNT(VM.Vaer_No), AVSR.INFORMATIONTYPE FROM AGVET_VAE_INFO VM, Agvet_Vae_Safe...
1) Using `trunc` ``` AND trunc(AVSR.ORIGINALRECEIVEDATE) BETWEEN to_date ('2000/04/1', 'yyyy/mm/dd') AND to_date ('2000/04/28', 'yyyy/mm/dd') ``` but this will ignore if any index is there on column `AVSR.ORIGINALRECEIVEDATE`, use it if there are no index on this column or if there is functional index using function ...
remove the +1 from the second date ``` SELECT DECODE(AVSR.INFORMATIONTYPE,'NULL','UNKNOWN','5','Infectious Agent Transmission Issue','4','Environmental Issue','3','Withdrawal Period Issue','2','Lack OF Expected Efficacy','1','Safety Issue') Infotype, COUNT(VM.Vaer_No), AVSR.INFORMATIONTYPE FROM AGVET_VAE_INFO VM, ...
How to fetch records between a given date range and both date range should include for searching records?
[ "", "sql", "database", "oracle", "" ]
If I had this: ``` NAME EYES==ID==HAIR Jon Brown==F9182==Red May Blue==F10100==Brown Bill Hazel/Green==F123==Brown ``` ...and I wanted to create a new ID column with the ID alone, and I know that everyone's ID starts with an 'F' and will end at the '=' how would I select a substring from...
You can use a Regular Expression: ``` regexp_substr('Hazel/Green==F123==Brown','(==F.+?==)') ``` extracts '==F123==', now trim the `=`: ``` ltrim(rtrim(regexp_substr('Hazel/Green==F123==Brown','(==F.+?==)'), '='), '=') ``` If Oracle supported lookahead/lookbehind this would be easier... Edit: Base on @ErkanHaspul...
The idea is to find the portion of the string you want using a regular expression. In the query below, notice the `()` characters that defines a sub-expression in the given regular expression. That is the magic part; you can use as many sub-expressions you want in a regular expression and select them using the final pa...
SQL Oracle | How would I select a substring where it begins with a certain letter and ends with a certain symbol?
[ "", "sql", "oracle", "select", "substring", "oracle-sqldeveloper", "" ]
I have a table with the following columns ``` NAME FRIEND ---------------------- Apple Flavour Flavour Apple New Banana Banana Flavour ``` I want to remove the columns having records with same combination for example apple, flavour and flavour, apple are same. I want only one record among the two ...
You could use **LEAST** and **GREATEST** functions to fetch the unique combination. For example, ``` SQL> WITH DATA AS( 2 SELECT 'apple' a, 'flavour' b FROM dual UNION ALL 3 SELECT 'flavour', 'apple' FROM dual UNION ALL 4 SELECT 'new', 'flavour' FROM dual UNION ALL 5 SELECT 'banana', 'fruit' FROM ...
To avoid duplicates, start with select all rows where name < friend. Otherwise, also return if the reversed name/friend pair doesn't exist. ``` select * from tablename t1 where t1.name < t1.friend or not exists (select 1 from tablename t2 where t1.name = t2.friend and t1.friend...
How to remove duplicate records from the table
[ "", "mysql", "sql", "oracle", "hive", "" ]
Good day everyone, I am hoping someone could help me with an issue I am having. I have a database that stores the amount of data that was reviewed on a hard drive. The values can either be Megabytes or Gigabytes. Example: ``` Hard Drive 1 100MB Hard Drive 2 2.5 GB Hard Drive 3 650 MB ``` My questio...
The basic idea is to get the size by `CASE` like ``` Size / CASE Unit WHEN 'KB' THEN 1000 * 1000 WHEN 'MB' THEN 1000 WHEN 'GB' THEN 1 WHEN 'TB' THEN 0.001 END ``` Example for SQL Server: ``` DECLARE @Table table ( Size decimal(18,3), Unit char(2) ) INSERT @Table...
If your schema defines the size and the 'unit multiplier' in *separate columns*, like this: ``` create table disks ( id int not null, size varchar(20) not null, mult_id varchar(2) ) go ``` Then create a table to map each string quantifier to the size (in MB) ``` create table mult ( id varchar(2) not null,...
Adding values of different sizes in SQL
[ "", "sql", "sql-server", "" ]
I am using a `RIGHT(LEFT())` method of stripping a string as each character needs to be put into its own holder so I can access it and use it for a report (each character needs to be in its own box for some reason). There are 16 characters usually but for space and to save repition I've slimmed down the code. What I ...
Just do it like: ``` CREATE table #StringSeparate ( col1 varchar(1), col2 varchar(1), col3 varchar(1), col4 varchar(1), col5 varchar(1), col6 varchar(1), col7 varchar(1), col8 varchar(1), ) INSERT INTO #StringSeparate SELECT LEFT(@string,1), RIGHT(LEFT(@string,2),1), RIGHT(LEFT(@string,3),1), RIGHT(LEFT(@string,4),1),...
Depending on you RDBMS I suppose I might prefer SUBSTRING: ``` INSERT INTO #StringSeparate SELECT LEFT(@string,1), SUBSTRING(@string,2,1), SUBSTRING(@string,3,1), ... RIGHT(@string,1) ```
Separated string into specific temp table colums
[ "", "sql", "" ]
**This is my question:** *Find the capital and the name where the capital includes the name of the country.* **This is my answer:** ``` SELECT name,capital FROM world WHERE capital=concat(name,"NULL") ``` I dont understand what should i do in the "WHERE" part. Should i do **capital=concat(name,something?)** or **...
Not sure what you're trying to do with the `NULL` there, but basically you if you want to find a capital that contains the name of the country, the usage of the `like` operator is definitely in order. Just slap a couple of wildcards (`%`) around it, and you should be good to go: ``` SELECT name, capital FROM world W...
`CONCAT` is not necessary here, you should be able to use: ``` WHERE [capital] LIKE '%[name]%' ```
Sql string search
[ "", "sql", "string", "search", "select", "" ]
first Table "teams" has TeamCode(varchar 5) and TeamName (varchar 20) second Table "season" has homeTeam (varchar 5) , Team2 (varchar 5), Gameday (date) homeTeam & Team2 are FKs that are connected to TeamCode PK table: teams | TeamCode | TeamName | |:-----------:|:--------------| | 1 | USA | | 2 | UK | | 3 |...
Try this ``` SELECT T1.Name As Host , T2.Name As Guest, S.Date FROM [dbo].[Season] as S Inner Join [dbo].[Team] as T1 on S.HostTeam = T1.ID Inner Join [dbo].[Team] as T2 on S.GuestTeam = T2.ID ```
``` SELECT ht.TeamName, at.TeamName, s.GameDay FROM teams AS ht INNER JOIN season AS s ON ht.TeamCode = s.Team1 INNER JOIN teams AS at ON s.Team2 = at.TeamCode ```
two foreign keys to same primary key select statement MYSQL
[ "", "mysql", "sql", "select", "foreign-keys", "" ]
Here is my sample data for the select statement ``` banner_id subject_code N00012301 MATH N00012963 ENGL N00012963 MATH N00013406 ENGL N00013406 ENGL N00013406 MATH N00013998 ENGL N00016217 MATH N00017367 MATH N00017367 ENGL N00017833 MATH N00018132 MATH N00019251 ENGL N000192...
Try this: ``` SELECT banner_id AS [COUNT] FROM @t WHERE subject_code IN ('ENGL', 'MATH') GROUP BY banner_id HAVING COUNT(DISTINCT subject_code) > 1 ``` If you want to just count then: ``` SELECT COUNT(*) FROM ( SELECT banner_id AS [COUNT] FROM @t WHERE subject_code IN ( 'ENGL', 'M...
If you want to see the banner\_ids, this should get you each `banner_id` where the `banner_id` exists with both `math` and `engl`: ``` SELECT banner_id FROM YourTable WHERE subject_code IN ('engl', 'math') GROUP BY banner_id HAVING COUNT(DISTINCT subject_code) > 1 ```
Want to count Distinct values in column 1 based on column 2 values
[ "", "sql", "sql-server", "t-sql", "" ]
In SQL Server, I can't seem to use an aliased column name in the `WHERE` clause This doesn't work ``` SELECT *, [dbo].[myFunc] (X.Prop1) AS Width FROM X WHERE Width > 0 ``` I have to do ``` SELECT *, [dbo].[myFunc] (X.Prop1) AS Width FROM X WHERE [dbo].[myFunc] (X.Prop1) > 0 ``` My concern is that SQL is execu...
When I try both ways, they have the exact same execution plan, so looks like the query optimizer is smart enough to find out that they are the same query and run it once... So both ways are OK I assume... But if want to use the subquery approach and use the alias you can use a something like this: ``` Select * from (...
I am not sure if it is calculated twice or not, but you can avoid this using `CROSS APPLY`: ``` SELECT *, Width FROM X CROSS APPLY (Select [dbo].[myFunc] (X.Prop1)) N(Width) WHERE Width > 0 ``` Look this [fiddle](http://sqlfiddle.com/#!3/9eecb7db59d16c80417c72d1/639) that selects the square of values that are grea...
Filter SQL query based on scalar function result
[ "", "sql", "sql-server", "" ]
Long time reader but first time poster so apologies for any mistakes in creating a post. I'm trying to work out the rates of sales for a product based on its time available and sales. ``` SELECT productname, datediff(day, MIN(DateAdded), getdate())/ nullif(SalesToDate,0) as [Days For A Sale] FROM TABLE ``` Pretty s...
you can use Case inside Aggregate Function as ``` SELECT productname, DATEADD(YEAR, 42, datediff(day, MIN(case when year(DateAdded) = '1970' then dateadd(YY,CEILING(datediff(YY,DateAdded,'1/1/2012')),DateAdded) else a end ),getdate())/nullif(SalesToDate,0)) as [Days For A Sale] FROM TABLE ``...
If you want to do it in the select, and specifically replace 1970 with 2012 then a `DATEADD` may help you out: ``` SELECT productname, DATEADD(YEAR, 42, datediff(day, MIN(DateAdded),getdate())/nullif(SalesToDate,0)) as [Days For A Sale] FROM TABLE ```
SQL replace specific date in a select
[ "", "mysql", "sql", "" ]
I have 2 tables with 3 columns that are suppose to have the same information. I would like have a query that selects only the rows that don't have a complete row match. Below is an example of the 2 tables I would like to match: Table 1 ``` ID FPRICE FPRODUCT 1 1 A 2 2 B 3 3 ...
Easier to verify if we build some DDL and fillwith sample data, but I think this would do it. It takes a full join to find records with a partial match and then filters out records with a full match. [sqlfiddle.com](http://sqlfiddle.com/#!6/163c8/1) ``` CREATE TABLE Table1 (ID INT, FPRICE INT, FPRODUCT CHAR(1)) INS...
Can you try this query? ``` SELECT DISTINCT t1.ID t1.FPRICE t1.FPRODUCT from Table1 t1 LEFT JOIN Table2 ON Table1.ID = Table2.ID AND Table1.FPRICE = Table2.TPRICE AND Table1.FPRODUCT= Table2.TPRODUCT WHERE Table1.ID is NULL or Table1.FPRICE is NULL or Table1.FPRODUCT is NULL or Table2.TPRICE is NULL or Table2.TPROD...
Finding unmatched rows of 2 tables in SQL
[ "", "sql", "sql-server", "join", "" ]
I have one table which has fields `X,Y,Z,BAGID.` The BAGID is in the form of (12345-400) where 12345 is the user's id and 400 is the BAG's id. I have another table which has fields `A,B,C,USERID.` The USERID is in the form of 12345 which is same as the first part of BAGID. So is it possible to join these two tables o...
You can use the [`SUBSTRING_INDEX`](https://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_substring-index) to extract `USERID` out of `BAGID`: ``` select Table1.X, Table1.Y, Table2.A, Table2.B, Table2.USERID from Table1 inner join Table2 on SUBSTRING_INDEX(Table1.BAGID, '-', 1) = Table2.USERID ``` ...
Sure, just join on LEFT(BAGID,5). Depending on the USERID DataType you may need to CAST it as well. If the USERID portion of BAGIT is variable length you first need to find the length using INSTR(BAGID, '-')
Inner join on two different fields of 2 different tables
[ "", "mysql", "sql", "" ]
I have 5 tables which are ``` - Project(PK Project_ID), - Bottles (PK Bottle_ID, FK Project_ID), - Plastics (PK Plastic_ID, FK Project_ID), - Glasses (PK Glass_ID,FK Project_ID) and - Cups (PK Cup_ID, FK Project_ID) ``` How can I get one SQL query to return the number of Bottles ,Plastics , Glasses and Cup per Pr...
``` select p.project_id, count(distinct bottle_id), count(distinct plastic_id), count(distinct glass_id), count(distinct cup_id) from project p left join bottles b on p.project_id = b.project_id left join plastics pl on p.project_id = pl.project_id left join glasses g on p.project_id = g.project_id left join cups c on ...
``` Create table Project (Project_ID int ) Create table Bottles ( Bottle_ID int, Project_ID int) Create table Plastics ( Plastics_ID int, Project_ID int) Create table Glasses ( Glasses_ID int, Project_ID int) Create table Cups ( Cups_ID int, Project_ID int) insert into Project (Project_ID) values (1) insert into B...
One SQL Query to get number of items from different tables reference in another table
[ "", "sql", "sql-server", "count", "" ]
I have a master table with one record: ``` employee Id ----------- 10 ``` and detail table with 4 records: ``` employee Id1 ----------- 10 20 10 10 ``` My join condition is `employee Id = employee Id1` with normal join type. My question is which of the following output table will I get? 1. Output employee Id tab...
For Normal join type, output is 3 rows **NORMAL JOIN** -It will give matching rows from both tables **MASTER OUTER JOIN** - It will give matching rows from MASTER table and all rows from DETAIL table ,rest of the rows are discarded. **DETAIL OUTER JOIN** - (just opposite above) It will give matching rows from DETAIL...
Output should be 3 records obviously.
Number of records using normal joiner in informatica
[ "", "sql", "informatica-powercenter", "joiner", "" ]
I have following query: ``` select user_id, trajectory_id, count(trajectory_id) from point group by user_id, trajectory_id ``` It returns following result: ![enter image description here](https://i.stack.imgur.com/evZXY.png) And I want to delete all records from `point` table where `count` in produced table is < 5. ...
``` delete p1 from point p1 join ( select user_id, trajectory_id from point group by user_id, trajectory_id having count(trajectory_id) < 5 ) p2 on p1.user_id = p2.user_id and p1.trajectory_id = p2.trajectory_id ```
I would do this with a simple correlated subquery: ``` delete from point where (user_id, trajectory_id) in (select user_id, trajectory_id from point group by user_id, trajectory_id having count(*) <...
sql delete based on group by
[ "", "sql", "postgresql", "sql-delete", "" ]
I've been trying to figure out how I can modify this query so that the result set does not include the numHits. I want the same results in the same order, just not have the numHits included. ``` SELECT `newel_inventoryKeywordIdDictionaryId`.`inventoryId` ,COUNT(`newel_inventoryKeywordIdDictionaryId`.`inventor...
Move the column from SELECT clause to ORDER BY clause: ``` SELECT `newel_inventoryKeywordIdDictionaryId`.`inventoryId` FROM `newel_inventoryKeywordIdDictionaryId` , `newel_inventoryDictionary` WHERE `newel_inventoryKeywordIdDictionaryId`.`dicId` = `newel_inventoryDictionary`.`dicId` AND ( ...
``` SELECT `newel_inventoryKeywordIdDictionaryId`.`inventoryId` FROM `newel_inventoryKeywordIdDictionaryId` , `newel_inventoryDictionary` WHERE `newel_inventoryKeywordIdDictionaryId`.`dicId` = `newel_inventoryDictionary`.`dicId` AND ( `newel_inventoryDictionary`.`word` = 'alabaster' OR `newel_inventoryDictiona...
Group and order by a column but donot include that column in results
[ "", "mysql", "sql", "group-by", "sql-order-by", "" ]
I am (still) new to postgresql and jsonb. I am trying to select some records from a subquery and am stuck. My data column looks like this (jsonb): ``` {"people": [{"age": "50", "name": "Bob"}], "another_key": "no"} {"people": [{"age": "73", "name": "Bob"}], "another_key": "yes"} ``` And here is my query. I want to se...
The error means just what it says: > more than one row returned by a subquery used as an expression The expression in the `WHERE` clause expects a single value (just like you substituted in your added test), but your subquery returns ***multiple*** rows. `jsonb_array_elements()` is a set-returning function. Assuming...
In your subquery: ``` SELECT (a->>'age')::float FROM (SELECT jsonb_array_elements(data->'people') as a FROM mytable) as b WHERE a @> json_object(ARRAY['name', 'Bob'])::jsonb ``` You selected all the rows of `mytable` all over again. That's why your subquery returns multiple values. **If you want to select rows...
JSONB: more than one row returned by a subquery used as an expression
[ "", "sql", "postgresql", "postgresql-9.4", "jsonb", "set-returning-functions", "" ]
I have a table ``` declare @t table (val int) insert INto @t (val) values (420), (420), (520), (520), (520), (620) select val, ROW_NUMBER() OVER (PARTITION BY val order by val) RN from @t ``` Returns output: ``` val RN ------ 420 1 420 2 520 1 520 2 520 3 620 1 ``` Desired output : ``` val RN 420 1 420 2 N...
This works: ``` declare @t table (val int) declare @n table( val int) insert INTO @n(val) values( NULL ) insert INto @t (val)values (420),(420),(520),(520),(520),(620) SELECT T2.val, T2.RN AS RN FROM ( select T.val AS GRP, T.val,ROW_NUMBER()OVER(PARTITION BY T.val order by T.val)RN from @t AS T union select DISTINCT...
This type of manipulation should really be done in the application. You can do this in SQL Server, but it is really more of an amusing trick, then a recommended answer. The idea is to join in the rows you want and then use `order by` to get the results in order: ``` select val, rn from ((select val, ROW_NUMBER() OVER...
how can i achieve Null row after every sequence
[ "", "sql", "sql-server", "" ]
these are the 2 columns(month,year). I want to create a single column out of them having an accurate date-time format('YYYY-MM-DD HH:MM:SS') and add as new column in the table. ``` Month year 12/ 3 2013 at 8:40pm 12/ 3 2013 at 8:39pm 12/ 3 2013 at 8:39pm 12/ 3 2013 at 8:38pm 12/ 3 2013 at 8:37pm ``...
I'm going to assume that the 12 is `month` and that 3 is `day` since you didn't specify. Also, you said you want `HH:MM:SS` but there is no seconds in your example so I don't know how you're going to get them in there. I also changed `8:37pm` to `8:37am` in your example to try both cases. **Query:** ``` select conc...
yea worked fine, thank you very much @GoBrewers14. You saved my day! a little mismatch, this is the correct one: ``` select concat_ws(' ', concat_ws('-', yr, month, day), concat_ws(':', hour, minutes)) date_time from ( select yr , case when length(month) < 2 then concat('0', month) else month end as month...
Merging two columns into a single column and formatting the content to form an accurate date-time format in Hive?
[ "", "sql", "regex", "hadoop", "hive", "datetime-format", "" ]
I'm using `SQL Server 2008` and I have the following stored procedure : ``` ALTER PROC [dbo].[spGetLatestLangId] @salt VARCHAR(50), @result VARCHAR(50) OUTPUT AS DECLARE @CheckStr AS VARCHAR(50) SET @CheckStr = @salt + '%' SET @result = (SELECT TOP 1 Id FROM Lang WHERE salt LIKE @CheckStr ORDER BY ...
I think you need to use: ``` SET @CheckStr = REPLACE(@salt, '_', '[_]') + '%' ```
> how do I escape underscore in LIKE clause Using the `ESCAPE` clause: ``` where some_column LIKE 'X/_%' ESCAPE '/'; ``` in your case: ``` WHERE salt LIKE @CheckStr ESCAPE '/' ``` You can use *any* character for the escape character (e.g. `ESCAPE '\'` or `ESCAPE '@'`) - it's a good idea to use one that is not part...
Escape underscore in LIKE
[ "", "sql", "sql-server", "" ]
My table structure: ``` consumer_id, signup_date, plan_id, subscription_date ``` It has multiple subscription\_dates for the same consumer\_id. What I need in the result is all fields with first (min) subscription\_date where plan\_id is not a specific value. Without the where clause I tried: ``` select consumer_i...
You can try this: ``` select consumer_id, signup_date, plan_id , min(subscription_date) over (partition by consumer_id) from myTable ``` If needed you can remove unneded rows with your where.
Use `NOT EXISTS` to return a row if no other row with same consumer\_id but earlier date exists: ``` select consumer_id, signup_date, plan_id, subscription_date from myTable t1 where not exists (select 1 from myTable t2 where t2.consumer_id = t1.consumer_id ...
Get rows for each user with early date values
[ "", "sql", "sql-server", "" ]
I have a database of baseball plays with a PlayerID and a TypeID (the kind of play: double, strike out, etc). The data looks something like this: ``` +----------+--------+ | playerid | typeid | +----------+--------+ | 2 | 4 | | 2 | 4 | | 2 | 7 | | 3 | 7 | | 3 | ...
In MySQL this group=wise maximum it is sadly not a simply as you want it to be. Here's a way to do it using a method similar to what is suggested in [ROW\_NUMBER() in MySQL](https://stackoverflow.com/questions/1895110/row-number-in-mysql) ``` SELECT a.* FROM ( SELECT playerid ,typeid ...
Would this work? ``` SELECT playertypecounts.* FROM (SELECT playerid, typeid, COUNT(*) as playcount FROM plays GROUP BY playerid, typeid) playertypecounts INNER JOIN (SELECT typeid, MAX(playcount) as maxplaycount FROM (SELECT playerid,...
Select ID having maximum count of another ID
[ "", "mysql", "sql", "count", "" ]
I need to select `employee_id` from this table, if there is 00001 is four times, I need to get it only once. How to write query for this scenario? ``` id company_ID Employee_ID Name Relationship Dob Age Gender 1 EMPL 00001 Choodamani Spouse 11-Aug-66 49 Female ...
You can use the `distinct` keyword: ``` SELECT DISTINCT Employee_ID FROM Employees ```
You can try with `distinct`: ``` select distinct Employee_ID from tbl ```
How to write query to select value without repeat same values again?
[ "", "mysql", "sql", "select", "" ]
The following query is working absolutely fine for me: ``` SELECT * From Customers WHERE Customers.ContactName = (SELECT FirstName FROM Employees as E, orders as O WHERE <condition> LIMIT 1); ``` However, if i use `LIKE` inst...
First, this query *should* not be working fine: ``` SELECT * From Customers WHERE Customers.ContactName = (SELECT FirstName from Employees as E, orders as O WHERE LIMIT 1); ``` Because `WHERE LIMIT 1` is not proper SQL. And, you should learn to use proper ...
Why not use a simple `INNER JOIN`: ``` SELECT Customers.* FROM Customers INNER JOIN Employees ON Customers.ContactName LIKE CONCAT('%', Employees.FirstName,'%') WHERE Employees.Foo = 'Bar' ``` Note: `+` is the addition operator and can not be used to concatenate strings.
Using 'LIKE' with the result of a SQL subquery
[ "", "mysql", "sql", "subquery", "sql-like", "" ]
I have a **SQL Database** containing **24 Columns** and about **24000 Rows**. I want to retrieve data from that **SQL Database**. I am new to **Android** and don't know how to use it. I found an **Android library** called [Realm](http://Realm.io/docs/java/latest/) but I couldn't find a way of **Converting SQL** to **R...
android uses SQLite. This is very similar to SQL. You would only need to have the app download the data from the server database and copy in into the local database. SQLite information can be found at <http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html> Converting from an SQL file has ...
Android comes with SQLite, this is what you should use. did you search anything like "Android and sql"? [android training on the subject](http://developer.android.com/training/basics/data-storage/databases.html) Edit: so you dont have an sql file, you have an online MySql database. can use [jdbc](http://www.oracle.com...
How to use SQL Database other means of Data Storage
[ "", "android", "mysql", "sql", "sql-server", "database", "" ]
I have a simple SQL Server 2008 update query using `LOWER(FIELD_NAME)` that should only update where `FIELD_NAME` contains uppercase characters. ``` UPDATE TABLE SET FIELD_NAME = LOWER(FIELD_NAME) WHERE FIELD_NAME *contains uppercase characters* ``` How can I select only columns with uppercase characters in the where...
You could use a case-sensitive collation: ``` UPDATE TABLE SET FIELD_NAME = LOWER(FIELD_NAME) WHERE FIELD_NAME LIKE '%[ABCDEFGHIJKLMNOPQRSTUVWXZ]%' COLLATE SQL_LATIN1_GENERAL_CP1_CS_AS ```
Try the following out: ``` UPDATE TABLE SET FIELD_NAME = LOWER(FIELD_NAME) WHERE FIELD_NAME LIKE '%[A-Z]%' Collate SQL_Latin1_General_CP1_CS_AS ``` If you also have other characters such as numbers then the you could also do the query as follows: ``` UPDATE TABLE SET FIELD_NAME = LOWER(FIELD_NAME) WHERE FIELD_NAME =...
SQL select fields containing uppercase characters
[ "", "sql", "sql-server", "sql-server-2008", "" ]
When executing my doDelete.php, this error message appears: " Cannot delete or update a parent row: a foreign key constraint fails (`fyp`.`book`, CONSTRAINT `book_user_key` FOREIGN KEY (`id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION) " the Delete query: ``` $queryDelete = "DELETE FROM user W...
Indeed, you have a constraint in book table, that does not let you delete a user as long as there are books added by that user: ``` CONSTRAINT `book_user_key` FOREIGN KEY (`user_id`) REFERENCES `fyp`.`user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ``` You can change it to ``` ON DELETE CASCADE ``` so that del...
You cannot create a user record because it has related records in *book* table. It is how foreign key constraint works. You created this constraint in this line: ``` FOREIGN KEY (`user_id`) REFERENCES `fyp`.`user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ``` To solve this problem you can: 1. Delete records in...
Error message: Cannot delete or update a parent row: a foreign key constraint fails
[ "", "mysql", "sql", "constraints", "" ]
I am sorry if this is duplicate. Please point me to correct question. I am using SQL SERVER 2008. I am using below query since I need to get data from 3 tables. ``` SELECT qc.FileID as [FileID], qc.QID1 as [QID1], xqs.SID1 as [SID1], xqc.CID1 as [CID1], xqs.Comments as [SComments], xqc.Comments as [CCom...
You could do something like this using `UNION ALL`: ``` SELECT qc.FileID AS [FileID1] ,qc.QID1 AS [QID1] ,xqs.SID1 AS [SID1] ,NULL AS [CID1] --assigning default value as null ,xqs.Comments AS [SComments] FROM QCTable(NOLOCK) qc JOIN QCSectionTable(NOLOCK) xqs ON qc.QCID = xqs.QCID LEFT JOIN QC...
The easiest way is `union all`: ``` select FileID1, QID1, SID1, null as cId1, SComments from table t union all select FileID1, QID1, SID1, cId1, CComments from table t; ``` If you have a large amount of data, it can be a bit faster to do this using `cross apply` or a `cross join`: ``` select v.* from table t cross ...
SQL : Split one row into two rows depending on column
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have to do a query without using views that displays the automobile brand that has the maximum number of cars that have a single owner. that's the table that I have ``` CAR(idcar, brand, name, year_p) OWNER(idowner,name, b_date) PROPERTY(idcar,idowner,date_b, date_s) ``` That's what I was writing.. ``` SELECT Car...
I think you were on the right path with your query, it's only need a little modification... First if you want to select brand with most owner than you should order them in descending order so the max will be at the top... And second you need to add WHERE clause which will exclude all owner that have more then one car....
This is too long for a comment. Your query is not correct. It returns the brands that have the most properties for its cars. That may or may not have to do with the number of owners. I'm sure there's a relationship of some sort ("no properties" --> "no owners" and vice versa). In any case, I don't know what you mean ...
SQL query creation
[ "", "mysql", "sql", "" ]
I have a client table from which I need to select data in the following order: ``` Gender Count ----------------- Female 10 Male 50 Unknown 2 ``` (The above table data is just as an example) To achieve this, I used the following SQL: ``` SELECT decode(gender, 'F', 'Female', 'M', 'Male', 'Unknow...
You could start of with a select on the genders (using an inline view), then do a `left outer join` on the results. This will guarantee that there is always a list of genders available to show in the first column: ``` SELECT g.gender , count(ID) "Count" FROM ( select 'Female' gender from dual union all...
You should normalize your data to hold a gender table. Or at least use one (view) in your Query like below, and do a OUTER join. And use standard date formats.. **EDIT:** For better readability and performance, you have to carefully categorize the gender. Here am presuming an additional category 'U' for unknown case....
How to write an SQL query that returns count = 0 when no records found in group
[ "", "sql", "oracle", "" ]
I have two unrelated tables: ``` contribution(id,amount, create_at, user_id) solicitude(id, amount, create_at, status_id, type_id, user_id) ``` I need to subtract the sum of the amount of the contribution and of the solicitude from a user, but that result can't to be negative. How can I do this? Function or query? ...
I interpret your remark `but that result can't to be negative` as requirement to return 0 instead of negative results. The simple solution is [**`GREATEST()`**](http://www.postgresql.org/docs/current/interactive/functions-conditional.html#FUNCTIONS-GREATEST-LEAST): ``` SELECT GREATEST(sum(amount) - (SELECT sum(a...
You can add an outer query to check the total value: ``` SELECT CASE WHEN total > 0 THEN total ELSE 0 END AS total FROM ( SELECT sum(contribution.amount) - (SELECT sum(solicitude.amount) FROM solicitude WHERE user_id = 1 AND status_id = 1) as total FROM contribution ...
Subtract two columns of different tables
[ "", "sql", "postgresql", "sum", "aggregate-functions", "subtraction", "" ]
I am having trouble trying to create a table using MS Access. I know for sure my problem lies in the "datetime" field but I can not figure what I am missing or doing wrong. When I click "run" I get the > "Syntax Error in Field Definition" ``` Create Table Appointments (DocID char(4) not null...
Time and procedure are reserved words, and therefore should be escaped: ``` Create Table Appointments (DocID char(4) not null primary key, PatID char(8) not null, [Day] varchar(8) not null, [Time] datetime n...
Here `Procedure` and `Time` are reserved words and so need to be escaped using `[]` like below. See [Documentation](https://support.microsoft.com/en-us/kb/286335) for more information ``` Create Table Appointments (DocID char(4) not null primary key, PatID char(8) ...
Create Table - Time Statement
[ "", "sql", "datetime", "ms-access", "ddl", "create-table", "" ]
I think this should be straightforward, but I'm at a loss. I want to return data in the columns that weren't used in the SQL statement HAVING clause without having to do a 2nd query. I'm using PostgreSQL, but this should be a fairly generic question. Here's the data: ``` CREATE TABLE sandbox ( ret_val character(10...
I would use a window function for this: ``` select ret_val, value1, value2 from (select s.*, count(*) over (partition by key1, key2) as cnt from sandbox ) s where cnt = 1; ``` As a note, you can also do this with aggregation, but I don't think the query is as clean: ``` select max(ret_val) as ret_val, max...
Here is a join version: ``` SELECT ret_val,value1,value2 from sandbox, ( SELECT key1,key2 from sandbox group by 1,2 HAVING count(*)=1 ) as keys where sandbox.key1 = keys.key1 and sandbox.key2 = keys.key2 ```
return column data not used in SQL HAVING query
[ "", "sql", "postgresql", "having-clause", "" ]
I have a table ``` T (variable_name, start_no, end_no) ``` that holds values like: ``` (x, 10, 20) (x, 30, 50) (x, 60, 70) (y, 1, 3) (y, 7, 8) ``` All intervals are guaranteed to be disjoint. I want to write a query in T-SQL that computes the intervals where a variable is not searched: ``` (x, 21, 29) (x, 51, 59)...
Since you didn't specify which version of SQL Server, I have multiple solutions. If you have are still rocking SQL Server 2005, then Giorgi's uses CROSS APPLY quite nicely. **Note:** For both solutions, I use the where clause to filter out improper values so even if the the data is bad and the rows overlap, it will ig...
Here is another version with `cross apply`: ``` DECLARE @t TABLE ( v CHAR(1), sn INT, en INT ) INSERT INTO @t VALUES ( 'x', 10, 20 ), ( 'x', 30, 50 ), ( 'x', 60, 70 ), ( 'y', 1, 3 ), ( 'y', 7, 8 ); SELECT t.v, t.en + 1, c.sn - 1 FROM @t t CROSS APPLY(SELECT TOP 1 * FROM @t WHERE v = ...
T-SQL query - row iteration without cursor
[ "", "sql", "sql-server", "t-sql", "" ]
I have a SQL Server database with three tables: **Trips**, **Slices**, and **Legs**. Each **Trip** has a one to many relationship with **Slices** and **Slices** has a one to many relationship with **Legs**. Trips represents a full trip, a slice represents only the outbound or return portions of a trip, and the legs r...
Ow, my brain hurts... Replace all of the question marks (3 of them) with the trip ID of the trip where you want to check for similar trips. ``` select distinct s.tripIDFK as tripId from Legs l left join Slices s on l.sliceIDFK = s.sliceId where s.tripIDFK != ? and not exists ( select carrier, flightNumber, departur...
Hope this helps. Just pass the base TripId (in @BaseTripID) with which you want to compare other records. I assume that you are concerned only about carrier,flightNumber,departureAirport,ArrivalAirport to match exactly with any other trip regardless of date fields. ``` create table Trips(tripId int,saleTotal int,quer...
Finding records in main table that match records in another table in SQL Server
[ "", "sql", "sql-server", "sql-server-2012", "" ]
``` DATEDIFF(MONTH, '1/1/2014', '12/31/2014') + 1 ``` This will give me 12. What if I do this: ``` DATEDIFF(MONTH, '1/1/2014', '12/30/2014') + 1 ``` It should give me 11 point something. How do I go about getting the exact number of months between these two dates? This needs to work for any combination of dates (an...
You could do the calculation yourself in the following way: ``` DECLARE @startdate date = '1/1/2014' DECLARE @enddate date = '12/30/2014' DECLARE @startday int = DATEPART(DAY, @startdate) DECLARE @endday int = DATEPART(DAY, @enddate) DECLARE @startdateBase date = DATEADD(DAY, 1 - @startday, @startdate) DECLARE @endda...
DATEDIFF with the MONTH option only returns an integer value. Using days or years would give you a rough "guesstimate" but still not exactly right (different number of days in a month/year so you can't just divide the days difference by 30). If you want exact you would need to write your own function to walk through t...
how do I get the EXACT number of months between two dates?
[ "", "sql", "sql-server", "monthcalendar", "" ]
I have a SQL Server table ("Activities") which has a column containing an ID, e.g. "10553100". This is the activity ID and is composed of two parts -> first 4 digits indicates which project it belongs to, and the last 4 digits indicates which sub project. I need to extract the project number from the `activityId` colu...
Use the `LEFT` function. ``` SELECT activityId, LEFT(activityId, 4) AS projectnumber FROM Activities ``` Or the `SUBSTRING` function. ``` SELECT activityId, SUBSTRING (activityId, 1, 4) AS projectnumber FROM Activities ``` And if you want too include your subprojectnumber `LEFT` and `RIGHT` functions. ``` SELECT ...
If the field is numeric then: ``` SELECT Col / 10000 FROM TableName ``` If char the: ``` SELECT LEFT(Col, 4) FROM TableName ```
Select the first N digits of an integer
[ "", "sql", "sql-server", "" ]
I have a MySQL database with about 20.000 entries where files are named `Name_Subname_XXXXX`. Because the files are named that way, the name that shows to the internet itself also get's that name when entered into the database. I wonder how can I in an easy way remove the `_` from the name and just keep `Name Subname ...
You can use MySQL's [REPLACE](https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_replace) method for strings: ``` UPDATE tbl SET filename = REPLACE(filename, '_', ' '); ```
You can use [`replace`](https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_replace): ``` select replace(col, '_', ' ') from tbl ```
Remove all characters from the string
[ "", "mysql", "sql", "replace", "" ]
I have a table like this: ``` WOTranID WOID Status DateCreated ---------------------------------------------- 1 5 Ready 6/6/2015 2 5 Pending 6/5/2015 3 7 Pending 6/9/2015 4 8 Scheduled 6/10/2015 ``` What I need is to select all WOID ...
First, select all WOIDs which have had a status of pending, then intersect that with the list of WOIDs whose current status is not pending (using `row_number()` to select the latest status per WOID). ``` (Select Distinct WOID from MyTable where Status = 'Pending') intersect (Select WOID from (Select WOID , St...
May be this: ``` select distinct t1.WOID from TableName t1 where Status <> 'Pending' and not exists(select * from TableName t2 where t2.WOID = t1.WOID and t2.DateCreated > t1.DateCreated) and exists(select * from TableName t3 where t3.WOID = t1.WOID and t3.DateCreated < t1.DateCreated and t3.Sta...
SQL Server : select where row was X but is not now X
[ "", "sql", "sql-server", "" ]
Okay, so I have a MySQL table called `entries` which contains the columns `name VARCHAR(255) NOT NULL` and `address VARCHAR(255)` The table has about a million sets of data. For every set of data, name has a value e.g. "john" whilst address is NULL. For example: ``` +------+---------+ | name | address | +------+---...
You can import the CSV file into a separate table using mysql LOAD DATA INFILE and then update the entries table using JOIN statement on the basis of similar column name. E.g: update entries a inner join new\_table b on a.name = b.name set a.address = b.address ; Here new\_table is imported from the CSV file.. Don't...
Create table1 and table2 ``` LOAD DATA INFILE '/path/theFile1.csv' INTO TABLE table1 FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\n' ``` Ditto for file2 into table2 Proceed
What would be the fastest way to insert this data
[ "", "mysql", "sql", "database", "performance", "csv", "" ]
I have a table (tblABC) which looks like ``` ----------------------------- BasicID | Filter 1| Filter2 | ------------------------------ 100 1 2 100 3 4 101 8 9 ``` I want to select the BasicID which has Filter1=1 and Filter2=4. ie I want to get the output as 100...
Try below ``` select basicid from tblABC where filter1 = 1 intersect select basicid from tblABC where filter1 = 4 ```
If the two filter values can be either in different rows or the same row, the `GROUP BY / HAVING` method will fail (in the same row case). This method will work in all cases (the `intersect` query by @Azar will work, too): ``` select distinct a.BasicID from tblABC as a join tblABC as b on a.BasicID = b.BasicID ...
Sql query for AND on multiple rows
[ "", "sql", "sql-server", "" ]
I have read the many posts regarding collapsing multiple table columns into a single column using FOR XML PATH, but I am not a database person and cannot make other posts' suggestions work. I expect my problem is easy to solve for an experienced SQL DB person. I have MS SQL Server 2012. I have 3 tables (table1, table2...
Similar to @MartianCodeHound I'd use STUFF ``` SELECT t1.eventId, STUFF((SELECT ',' + t3.stringValue FROM TABLE2 t2 JOIN TABLE3 t3 ON t2.valueId = t3.valueId WHERE t2.eventId = t1.eventId ORDER BY t3.stringValue FOR XM...
Try the method in [this post](https://stackoverflow.com/questions/273238/how-to-use-group-by-to-concatenate-strings-in-sql-server). It's one of my favorites. ``` SELECT eventID, STUFF(( SELECT ', ' + stringValue FROM table1 t2 WHERE (t2.eventID = t1.eventID) FOR XML PATH('')) ,1,2,'') AS NameV...
SQL Query using FOR XML PATH that works right
[ "", "sql", "t-sql", "sql-server-2012", "" ]
In sql Server I join two query using *UNION* and my "Address" column has *nText* datatype so it's have an issue in Distinct. So i have to convert Address column *nText* to *varchar* but in output i got symbolic data in Adress. Actual data is in our local 'Gujarati' Language.
`varchar:` Variable-length, non-Unicode character data. The database collation determines which code page the data is stored using. `nvarchar:` Variable-length Unicode character data. Dependent on the database collation for comparisons. so change your type `varchar` to `nvarchar` it will sort your issue.. Same issue...
Please use "nvarchar" instead of "varchar"
data convert to symbolic language
[ "", "sql", "sql-server", "" ]
table1 K ``` Date id 2015-01-01 10 2015-01-02 10 2015-01-03 10 2015-01-04 10 2015-01-05 10 2015-01-06 10 ``` table2 H ``` Date id Holiday 2015-01-03 10 a holiday day ``` I want to exclude holidays from my `Date` column and create a new column like `AS new_dates`. So the ou...
Now edited. I was suggesting `EXCEPT ALL`, but Oracle has `MINUS` instead, according to MTO's answer. ``` select date, id from table1 MINUS select date, id from table2 ``` Or `NOT EXISTS`: ``` select date, id from table1 t1 where not exists (select 1 from table2 t2 where t1.date = t2.date ...
Simple ``` select date, id from table1 where not exists(select 'x' from table2 where table1.date = table2.date) ```
Exclude holidays in Oracle table
[ "", "sql", "oracle", "" ]
Is there any value which I can place in a SQL IN clause which will guarantee that the clause will evaluate to false? ``` SELECT * FROM Products WHERE ProductID IN (???) ``` Is there anything I could replace ??? with to guarantee no rows will be returned?
Replace with `NULL`. There is no better guarantee! Because no other value can equal to `NULL`, even `NULL` itself. And this is kinda universal value for any type(as @zohar-peled mentioned).
Use `NULL` ``` SELECT * FROM Products WHERE ProductID IN (NULL) ``` As this will return nothing
SQL IN clause which is guaranteed to evaluate to false
[ "", "sql", "sql-server", "sql-in", "" ]
I am trying to use an Oracle SQL update statement using a 'SWITCHED' case statement as mentioned below: ``` update MY_TABLE SET STATE_ABBREVIATION= (CASE STATE WHEN 'MAHARASHTRA' THEN 'MH' WHEN 'ASSAM' THEN 'AS' WHEN 'HIMACHAL%' THEN 'HP' ... ELSE STATE END ); ``` I got this clue from the thread [SQL - WHERE clause...
You'll have to use the searched version in all cases. See the [syntax diagram](http://docs.oracle.com/cd/B19306_01/server.102/b14200/expressions004.htm)
You can use `LIKE` in all your conditions as there is no difference between `= 'aaaa'` and `LIKE 'aaaa'` in terms of output ``` update MY_TABLE SET STATE_ABBREVIATION= (CASE WHEN STATE LIKE 'MAHARASHTRA' THEN 'MH' WHEN STATE LIKE 'ASSAM' THEN 'AS' WHEN STATE LIKE 'HIMACHAL%' THEN 'HP' ... ELSE STATE END ); ```
Updating table using wildcard in Switch case statement
[ "", "sql", "oracle", "" ]
i have items table which is having Size as follows: ``` 1sq.mm. 1.5sq.mm. 0.5sq.mm. 2.5sq.mm. 0.75sq.mm. 4sq.mm. 20mm 25mm 20mtr 75mm x 50mm 100mm x 50mm 100mm x 100mm 75mm x 75mm ``` i wanted to display it has ``` 0.5sq.mm. 0.75sq.mm. 1.5sq.mm. 2.5sq.mm. 4sq.mm. 20mm 20mtr 25mm 75mm x 50mm 75mm x 75mm 100mm x 50mm ...
Try this: ``` SELECT Sizes FROM Items ORDER BY CAST(LEFT(Sizes, PATINDEX('%[a-z]%', Sizes)-1) as numeric(9, 2)) ``` that's assuming your data will always be number followed by at least one alphabetic char. [sql fiddle (thanks to matt!)](http://sqlfiddle.com/#!3/577e4/8)
Use `REPLACE` in the `ORDER BY` ``` SELECT Sizes FROM Items ORDER BY CAST(REPLACE(Sizes,'sq.mm.','') as NUMERIC(9,2)) ``` OUTPUT: ``` Sizes 0.5sq.mm. 0.75sq.mm. 1sq.mm. 1.5sq.mm. 2.5sq.mm. 4sq.mm. ``` SQL Fiddle: <http://sqlfiddle.com/#!3/ad91f/3/0>
how to sort alphanumeric data in sql..?
[ "", "sql", "sql-server", "sql-server-2008", "sql-server-2012", "" ]
My table data looks like this ``` declare @t table (name varchar(10), amt int, dt datetime) insert into @t (name, amt, dt) values ('meeseva',100,'06-17-2015'), ('meeseva',200,'06-17-2015'), ('meeseva',200,'06-17-2015'), ('meeseva',100,'06-16-2015'), ('meeseva',100,'06-15-2015'), ('meeseva',100,'06-14-...
you can try this ``` ;WITH ranking AS( SELECT name, SUM(amt) [sum], dt, RANK() OVER (PARTITION BY dt ORDER BY SUM(amt) DESC, name -- use recordid here to order by sum then recordnumber ) AS rnk FROM @t WHERE dt >= DATEADD(DAY, -4, CONVERT(DATE, GETDATE())) GROUP BY name, d...
Please, read my comment to the question. Here is a sample query: ``` SELECT * FROM ( SELECT *, ROW_NUMBER() OVER(PARTITION BY dt ORDER BY amt DESC) AS RowNo FROM @t ) T WHERE RowNo IN (1, 2) ORDER BY dt DESC ``` **[EDIT]** More adequate sample to your description of issue: ``` SELECT t.* FROM ( SELECT ...
how to get top 2 highest sum amounts per day
[ "", "sql", "sql-server", "" ]
I have two columns `X` and `Y` and a where statement as following: ``` WHERE (x=0 or x=1 or x=4 or x=6 or x=7 or x=12 or x=75) and (y=0 or y=1 or y=4 or y=6 or y=7 or y=12 or y=75) ``` since it's the same condition on both columns of the same table is there a way to short it? Something like `x and y are (0 or...
Provided that you don't need it to use an index on `x` or `y`, the simplest way is probably: ``` ...WHERE ARRAY[x,y] <@ ARRAY[0,1,4,6,7] ```
You may put the values into an array and the array into a [CTE](http://www.postgresql.org/docs/current/static/queries-with.html). Assuming the existence of `tablename(x int, y int)`: ``` with list(arr) as (select array[0,1,4,6,7]) select x,y from list,tablename where x=any(arr) and y=any(arr); ```
Check same long condition on two columns
[ "", "sql", "postgresql", "" ]
I have a table allData ``` id name 1 meat 2 chicken 3 fish 4 chicken 5 fish 6 chicken ``` and table relevantData ``` id name 1 meat 2 fish ``` I want to count the total number of occurrence per name in `allData`, but only for names which appear in `rel...
Change the point of view, you are interested in `relevantData`, that's the base of your query. You can use a correlated subquery, no need to use join or group-by: ``` SELECT rd.name, (SELECT COUNT(*) FROM allData ad WHERE rd.name = ad.name) AS Count FROM relevantData rd ``` `Demo`
You can try the following. ``` SELECT COUNT(*) FROM allData WHERE name in (SELECT name from relevantData) GROUP BY name ```
Count the number of entries in the table
[ "", "sql", "count", "" ]
I have a problem with something in SQL, let's see an example of database : ``` CREATE TABLE person( //Employee pe_id PRIMARY KEY NOT NULL AUTO_INCREMENT, pe_name VARCHAR(20), pe_office VARCHAR(20) ); CREATE TABLE project( //Mission pr_id PRIMARY KEY NOT NULL AUTO_INCREMENT, pr_name VARCHAR...
You solve this problem by not having this as a primary key. Primary keys cannot be NULL or, if they're composite primary keys, cannot contain NULL. *Make it a unique index instead*. Create an autonumber field for the primary key. I think this is better solution in your case * Primary Key: Can be only one in a table ...
Maybe you should do this: Before insert disable constraint: ``` ALTER INDEX fk_as_pe_id ON assignment DISABLE; ``` After insert enable it: ``` ALTER INDEX fk_as_pe_id ON assignment REBUILD; ```
Insert null value in an association table
[ "", "sql", "" ]
We have a PostgreSQL database with billions of entries in the form: ``` CREATE TABLE entry ( session integer NOT NULL, time integer NOT NULL, key text NOT NULL, data text NOT NULL ) ``` In this database `key` is a developer-defined string, while `data` is user-defined content. In other words, while there are ...
There is no built-in facility to do what you want, at least in PostgreSQL. Doing it effectively would require signifciant changes to how data is stored, as currently each row is independent of all other rows (well, except TOAST pointers for out-of-line stored data that's unchanged in an UPDATE). A column store could do...
You could normalize `key` into a domain-table, and add a FK to that. Below, I add a numerical FK pointing to a domain-tabel, but you could just as wel use the `key` text field to refer to the table of allowable strings. (it would make your table a bit fatter, but it would also make the updates/inserts a bit simpler) An...
(Automatically) convert SQL strings to 'enums'?
[ "", "sql", "performance", "postgresql", "" ]
There is a table `Table1` with rows shown below. Column `Label` stores priority for column `Tag`. Also in column `Label` - L1 is first priority, L2 is second and L3 is least priority. I have `Value` column which holds values for tag and which can be null. ``` RecordNo. Lable Tag Value --------------------------...
You can use `ROW_NUMBER`: ``` ;WITH Cte AS( SELECT *, RN = ROW_NUMBER() OVER(PARTITION BY Tag ORDER BY Lable) FROM Table1 WHERE Value IS NOT NULL ) SELECT RecordNo, Lable, Tag, Value FROM Cte WHERE RN = 1 ``` [**SQL Fiddle**](http://sqlfiddle.com/#!6/333bf/1/0)
cte with Min should do the trick ``` ;WITH cte AS ( SELECT Tag, MIN(Lable) AS Lable FROM Table1 WHERE Value IS NOT NULL GROUP BY Tag ) SELECT * FROM Table1 t1 JOIN cte c ON t1.Lable = c.Lable AND t1.Tag = c.Tag ```
Need SQL query to get conditional output
[ "", "sql", "sql-server", "" ]
I want update string (`varchar`) column in my database. I want to concatenate ',' + value. This is working, but I don't want to add ',' (comma) if value in database column is empty. It does not make sense to have comma at beginning. ``` UPDATE ImportState SET ClientValidationRemark = ClientValidationRemark + ',' + @...
Well, let me start by saying that keeping delimited string in a single column is a terrible database design, with only one exception: when the data is never used in sql and is needed as a delimited string in the application. In over 16 years of programming, I've only one time stored values like this, and it was exactly...
Here's an untested sample ``` UPDATE ImportState SET ClientValidationRemark = CASE ClientValidationRemark WHEN Null THEN @ClientValidationRemark WHEN '' THEN @ClientValidationRemark ELSE ClientValidationRemark + ',' + @ClientValidationRemark END WHERE Id=@Import...
SQL string concatenation, separated by ',' only when column is not null
[ "", "sql", "sql-server", "string-concatenation", "" ]
I'm a SQL newbie, in that case, I want to perform an IF..THEN in SQL SELECT statement, I try to write code like this, but it returns an error syntax Here's my code : ``` SELECT *,IF(total_skor <= 100 AND total_skor >= 80,"Amat Baik") AS pred FROM rekap_nilai ORDER BY id ASC ``` Can you tell me what's wrong in my cod...
You missing else part in your query otherwise your query ok.Below query with else part. ``` SELECT *,IF(total_skor <= 100 AND total_skor >= 80,"Amat Baik",NULL) AS pred FROM rekap_nilai ORDER BY id ASC; ```
The MySQL `IF` function takes *three* arguments. The first is evaluated as a boolean expression, if it evaluates to true (any non-zero integer value), the function returns the *second* argument, otherwise, it returns the *third* argument. Your IF is missing a third argument, a value to return when the boolean expressi...
Code for IF…THEN in SQL SELECT
[ "", "mysql", "sql", "" ]
There is open date `2015-05-19 10:40:14` and close date `2015-05-20 09:21:11` when I subtract them I am getting (close\_date.date\_value - open\_date.date\_value) some `9.45104166666666666666666666666666666667E-01` value I want to ignore the time 10:40:14 and 09:21:11 from 2 dates similarly I am subtracting (SYSDATE...
From **performance** point of view, I would not use **TRUNC** as it would suppress any regular **index** on the date **column**. I would let the date arithmetic as it is, and **ROUND** the value. For example, ``` SQL> SELECT SYSDATE - to_date('2015-05-20 09:21:11','YYYY-MM-DD HH24:MI:SS') diff, 2 ROUND( 3...
You can use DATEDIFF function. Here is the code ``` SELECT DATEDIFF(DAY, CONVERT(DATETIME, '2015-05-19 10:40:14'), CONVERT(DATETIME, ' 2015-05-20 09:21:11')) ```
How to mask date format in sql?
[ "", "sql", "oracle", "oracle11g", "date-arithmetic", "" ]
I have 2 tables that I need to update: Table A consists of: ID, personName, Date, status Table B consist of: PersonID, Date, status For every row in A there can be multiple rows in B with the same personID I need to "loop" over all results from A that the status=2 and update the date and status to 1. Also, for eve...
Here is an example using the `output` clause: ``` declare @ids table (id int); update table1 set status = 1 output inserted.id into @ids where status = 2; update table2 set status = 1, date = getdate() where personid in (select id from @ids); ```
Question has been asked before: [How to update two tables in one statement in SQL Server 2005?](https://stackoverflow.com/questions/2044467/how-to-update-two-tables-in-one-statement-in-sql-server-2005) it is not possible to update multiple tables at once. Summary answer from that question: You can't update multiple...
How to update multiple tables with single query
[ "", "sql", "sql-server", "" ]
What's the CTE syntax to *delete* from a table, then *insert* to the same table and return the values of the *insert*? Operating on 2 hours of sleep and something doesn't look right (besides the fact that this won't execute): ``` WITH delete_rows AS ( DELETE FROM <some_table> WHERE id = <id_value> RETURNING * )...
Your question update made clear that you cannot do this in a single statement. Packed into CTEs of the same statement, both operations (`INSERT` and `DELETE`) would see the same snapshot of the table and execute **virtually at the same time**. I.e., the `INSERT` would still see all rows that you thought to be deleted ...
``` CREATE TABLE test_table (value TEXT UNIQUE); INSERT INTO test_table SELECT 'value 1'; INSERT INTO test_table SELECT 'value 2'; WITH delete_row AS (DELETE FROM test_table WHERE value='value 2' RETURNING 0) INSERT INTO test_table SELECT DISTINCT 'value 2' FROM (SELECT 'dummy') dummy LEFT OUTER JOIN de...
SQL CTE Syntax to DELETE / INSERT rows
[ "", "sql", "postgresql", "common-table-expression", "postgresql-9.2", "" ]
My table: ``` ID Name Status1 Status2 ------------------------------------- 1 foo bar grain 2 bar foo sball 3 foo bar grain 4 far boo sball ``` I need for it to actually come out like this: ``` ID Name Status ...
You can use `union all` (or `union`, it depends on what you want to get in case `Status1` and `Status2` are the same): ``` select ID, Name, Status1 as Status from tbl union all select ID, Name, Status2 from tbl ``` [**SQLFiddle**](http://sqlfiddle.com/#!4/66ef90/2)
Here's another solution: ``` WITH counter AS (SELECT LEVEL lvl FROM dual CONNECT BY LEVEL <= 2) SELECT t.ID ,t.NAME ,CASE c.lvl WHEN 1 THEN t.status1 WHEN 2 THEN t.status2 END status FROM test_table t CROSS JOIN counter c; ``` The hierarchical query is something you'll see qu...
Merge results from two separate columns into one elongated column
[ "", "sql", "oracle", "select", "" ]
I came across a question while buidling schema for my application. When to use `varchar(max)` and `nvarchar(max)`. I mean the exact use cases where it should be applied. I have surfed in net too but I was able to get the exact answer. Could anyone suggest some exact usecase.
This is for Microsoft **SQL Server**: `NVARCHAR` is **Unicode** - 2 bytes per character, therefore max. of 1 billion characters; will handle East Asian, Arabic, Hebrew, Cyrillic etc. characters just fine. `VARCHAR` is **non-Unicode** - 1 byte per character, max. capacity is 2 billion characters, but limited to the ch...
Varchar(max) Varchar fields can be of any size up to a limit, which varies by databases: an Oracle 9i database has a limit of 4000 bytes, a MySQL database has a limit of 65,535 bytes (for the entire row) and Microsoft SQL Server 2005 has a limit of 8000 characters (unless varchar(max) is used, which has a maximum stor...
Difference between Varchar(max) and nvarchar(max)
[ "", "sql", "sqldatatypes", "" ]
I have this records from my `users` table: ``` user_id first_name last_name gender email ******* ********** ********* ****** ***** 229 Natalie Fern F natalie.fern@hotmail.com ``` and I want to search same `First Name` & `Last Name` from `first_name` OR `last_name`. I have created sql query b...
You are using the `LIKE` operator for `first_name` and `last_name` as follows: ``` LIKE '%Natalie Fern%' ``` This will only match strings which contain *anything* followed by 'Natalie Fern' followed by *anything*. But since the first and last name columns only contain (surprise) the first and last names, your query i...
Try this [Sql Fiddle](http://sqlfiddle.com/#!3/8edd6d/1) Function ``` CREATE FUNCTION [dbo].[fn_Split](@text varchar(8000), @delimiter varchar(20)) RETURNS @Strings TABLE ( position int IDENTITY PRIMARY KEY, value varchar(8000) ) AS BEGIN DECLARE @index int SET @index = -1 WHILE (LEN(@text) > 0) BEGIN ...
SQL find same value on multiple filelds with like operator
[ "", "mysql", "sql", "search", "sql-like", "" ]
In my database each row has a column for average rating. Now lets say I have thousands of rows with a variety of averages such as `4.45 4.78 3.21 2.13 4.91` How would I get the rows with the top 3 highest average?
You can order rows in descending with `order by average_rating desc` and `limit` output to the top 3 results: ``` select average_rating from tbl order by average_rating desc limit 3 ```
Order the avg by `DESC` order to find largest avergaes and then `LIMIT 5` to find the top 5 avg ``` SELECT avg FROM table_name ORDER BY avg DESC LIMIT 5; ```
find top entries in MYSQL database
[ "", "mysql", "sql", "" ]
Not being experienced with SQL, I was hoping someone could help me with this. I have a empty temp table, as well as a table with information in it. My outline of my query as it stands is as follows: ``` CREATE TABLE [#Temp] (ID Int, Field1 Varchar) INSERT INTO [#Temp] SELECT ID, Field1 FROM [Other_table] ...
You can only use one target table for each insert statement. therefore, keeping `field1` as null seems like the easy way to go: ``` INSERT INTO [#Temp] SELECT ID, CASE WHEN ID IN (ID1, ID2, ID3...) THEN Field1 END FROM [Other_table] ``` the case statement will return `null` id the ID is not in the list. **Update** ...
The quickest fix to your existing solution is to get all the values from other table which doesn't exists in your temp table. I have marked Field1 as NULL for all those Id's. ``` CREATE TABLE [#Temp] (ID Int, Field1 Varchar) INSERT INTO [#Temp] SELECT ID, Field1 FROM [Other_table] WHERE ID IN (ID1, ID2,...
SQL INSERT INTO WITH SELECT query
[ "", "sql", "sql-server", "select", "insert-into", "" ]
I have the following table: ![enter image description here](https://i.stack.imgur.com/W8GKe.png) What i want is the following result: ``` InteractionID - OpenTime - CloseTime ``` Opentime is the `DATE_STAMP` where `UPDATE_TYPE = "Open"` and CloseTime is is the `DATE_STAMP` where `UPDATE_TYPE = "Close"` I have the ...
You can try this query ``` SELECT DISTINCT A.INTERACTION_ID as idd, A.DATE_STAMP AS OpenTime, B.DATE_STAMP AS CloseTime, FROM dbo.SD_INTERACTIONS_HISTORY A JOIN dbo.SD_INTERACTIONS_HISTORY B ON A.INTERACTION_ID = B.INTERACTION_ID AND A.UPDATE_TYPE = 'Open' AND B.UPDATE_TYPE = 'Close' WHERE DATEDIFF...
something like this? ``` SELECT INTERACTION_ID, update_open, update_close, datediff('d',update_open,update_close) AS diff FROM (SELECT INTERACTION_ID, MAX(CASE WHEN update_type = 'Open' THEN DATE_STAMP ELSE NULL END) AS update_open, MAX(CASE WHEN update_type = 'Close' THEN ...
Select record and get closeTime and OpenTime from the same table
[ "", "sql", "sql-server", "" ]
My SQL skills are quite limited. I'm in my second year of computer science at a technical college. I'm building a windows forms application that will allow the BAS director at my college to keep track of students and their progress throughout the courses. I have complete control over the database design so if you think...
Using a subquery with a group by and having statement you can come up with something similar to this: ``` SELECT * FROM Students WHERE StudentID NOT IN ( SELECT s.StudentID FROM Students s JOIN CourseEnrollment ce ON s.StudentID = ce.StudentID JOIN Courses c ON ce.CourseID = c.CourseID ...
Try something like this, I typed it by hand, so there could be a typo. ``` SELECT * FROM Students s inner join (select StudentID, count(0) as CrsEnrollCount from CourseEnrollment ce inner join Courses c on ce.CourseID = c.CourseID where ce.EnrollmentStatus = 3 AND Courses.CreditSection = 1)...
Improve my SQL Select statement to select students who have not fully completed a section
[ "", "sql", "sql-server", "linq", "t-sql", "" ]
If a SQL Server 2012 table has 2 `varchar(max)` columns that are rarely used and causing a table to grow rapidly, does it make sense to split into a separate table? Data in the two `varchar(max)` columns is used to store raw JSON responses from an API. If stored in a separate table, rows would be truncated to only in...
> If stored in a separate table, rows would be truncated to only include previous 6 months, reducing table size of first table. The rows would have to be deleted, not truncated, and then the BLOB space would have to be reclaimed by running `ALTER INDEX ... REORGANIZE WITH (LOB_COMPACTION = ON)` If you'd store instead...
Just to give you a hint. You can use `SPARSE` on a rarely used column. Example: ``` CREATE TABLE myTable ( id int identity(1,1), name nvarchar(100), blob nvarchar(max) SPARSE, blob2 nvarchar(max) SPARSE ) ``` Sparse will just left a small marker inside the page. But it's mostly bad practice to have `...
SQL Server 2012 - Separate 2 Varchar(max) columns to separate table?
[ "", "sql", "sql-server", "database", "database-design", "" ]
I have a query that it's select statement is this: ``` select Greatest(p.price,0) as newprice, sum(q.qty) as qty from .... ``` it gives me: ``` newprice qty 10 1 0 1 100 2 1 2 ``` I want to multiply newprice with qty to get: ``` newprice qty result 10 ...
You can just repeat what you wrote: ``` select Greatest(p.price,0) as newprice, sum(q.qty) as qty, Greatest(p.price,0) * sum(q.qty) as result from ... ``` or, you can wrap your *select statement* to *temporary derived table* ([PostgreSQL: using a calculated column in the same query](https://stackoverflo...
Query should be like this : ``` select *, newprice*qty from ( select Greatest(p.price,0) as newprice, sum(q.qty) as qty from .... ) T ``` OR ``` select Greatest(p.price,0) as newprice, sum(q.qty) as qty, Greatest(p.price,0)*sum(q.qty) as result from .... ``` UPDATE : you are using `group by` in your query ...
PostgreSQL: How to multiply two columns and display result in same query?
[ "", "sql", "postgresql", "" ]
Say I have a query that returns the following ``` ID SomeValue 1 a,b,c,d 2 e,f,g ``` Id like to return this as follows: ``` ID SomeValue 1 a 1 b 1 c 1 d 2 e 2 f 2 g ``` I already have a UDF calls Split that will accept a string and a delimte...
Alternatively, you could use XML like so: ``` DECLARE @yourTable TABLE(ID INT,SomeValue VARCHAR(25)); INSERT INTO @yourTable VALUES (1,'a,b,c,d'), (2,'e,f,g'); WITH CTE AS ( SELECT ID, [xml_val] = CAST('<t>' + REPLACE(SomeValue,',','</t><t>') + '</t>' AS XML) FROM @yourTable ) SELECT ...
You use `cross apply`. Something like this: ``` select t.id, s.val as SomeValue from table t cross apply dbo.split(SomeValue, ',') as s(val); ```
Split comma separated string table row into separate rows using TSQL
[ "", "sql", "sql-server-2008", "t-sql", "" ]
> There is a table a\_status\_check with the following data: ![enter image description here](https://i.stack.imgur.com/MSt98.png) The requirement is: If status LC and BE both are present, then consider only LC. Otherwise, consider BE. Ignore other codes for that id. So, the result should be like: ![enter image desc...
Use analytical functions: ``` select distinct id, first_value (status) over (partition by id order by status desc) status, first_value (amt ) over (partition by id order by status desc) amt from tq84_a_status_check where status in ('LC', 'BE') order by id; ``` Testdata: ``` create table tq84_a_status_c...
You can try this: ``` SELECT id, status, amt FROM yourTable yt INNER JOIN ( -- get only max SELECT id, MAX(status) as status FROM yourTable GROUP BY id ) as onlyMax ON yt.id = onlyMax.id AND yt.status = onlyMax.status ```
Query to filter records based on specific conditions
[ "", "sql", "oracle", "oracle11g", "" ]
I have a SQL query that returns all employees. It gives me an error because it expects after the `WITH( )`, it expects a `SELECT` statement. But if I would like to filter the result a second time, how do I work around using IF-ELSE IF? Note: My SQL might sound a little confusing (i.e.: if @Gender = Male, look for all...
Why not do the filtering in CTE itself like ``` DECLARE @Gender VARCHAR(10) SET @Gender = 'Female' WITH queryResult AS ( SELECT * FROM Employees WHERE Age >= 50 AND Gender = @Gender ) select * from queryResult; ``` **EDIT:** In that case change your CTE with a `CASE` expression like below ``` DECLARE @Gende...
Why not just: ``` DECLARE @Gender VARCHAR(10) SET @Gender = 'Female'; WITH queryResult AS ( SELECT * FROM Employees WHERE Age >= 50 ) SELECT * From queryResult WHERE Gender = @Gender ``` EDIT: If your WHERE clauses are very different you are likely better off putting the conditional on the outside. Putting the ...
How to filter a SELECT result with IF condition?
[ "", "sql", "sql-server", "t-sql", "" ]
I'm a first time poster and new to SQL, as are my colleagues. I have a column of numbers (let's just call it "numbers") and the values in it range from 1-9999. I need to create a grouping column (let's call it "numbers level") and assign the values of AA to all numbers from 1-999, BB from 1000-6999 and CC for 7000-...
This would be easiest with a case statement (assuming you're using sql-server; if not, please add tags for the correct version). ``` Select [Numbers] , case when [Numbers] between 1 and 999 then 'AA' when [Numbers] between 1000 and 6999 then 'BB' when [Numbers] between 7000 and 9999 then 'CC' e...
The grouping column has to exist, but you could use a `case` instead. ``` select nr, case when nr <= 999 then 'AA' when nr <= 7000 then 'BB' else 'CC' end as NrLevel from Numbers ```
SQL: GROUP BY for number ranges?
[ "", "sql", "group-by", "" ]
I need to increment each field in a column by 1 starting from 2866. I've built the following query, but all it does is set each field to 2867 as opposed to 2868, 2869 etc... ``` DECLARE @a int SET @a = 2866 UPDATE view_kantech_matched SET image_id = @a + 1 WHERE image_id = null ``` Any suggestions? Thanks
The general structure for doing this would be: ``` ;WITH Numbered as ( SELECT *,ROW_NUMBER() OVER (ORDER BY <some column>) rn FROM view_kantech_matched WHERE image_id is NULL ) UPDATE Numbered SET image_id = 2865 + rn ``` But I don't know what `<some column>` would be.
``` DECLARE @a int SET @a = 2866 UPDATE view_kantech_matched SET image_id = @a, @a=@a + 1 WHERE image_id = null ```
Increment each field in a column by 1 - SQL Server 2008
[ "", "sql", "sql-server", "t-sql", "" ]
I am trying to make sql query between two columns. table\_1 ``` ID ProductName ProductDescription 1 Prod_1 Description_1 2 Prod_2 Description_1 3 Prod_3 Description_1 4 Prod_4 Description_1 5 Prod_5 Description_1 ``` table\...
As i am right with your requirenments this untested query should work: ``` $query = "SELECT a.ID, a.ProductName, b.ID, b.Product, b.Partnerm, case when b.id is null then 0 else 1 end FROM table_1 a LEFT JOIN table_2 b ON a.ID = b.ID and b.Partner = 21" ```
Try this ``` $query = "SELECT a.ID, a.ProductName, b.ID, b.Product, b.Partnerm case when b.id is null then 0 else 1 end FROM table_1 a LEFT JOIN table_2 b ON a.ID = b.Product and b.Partner = 21" ```
sql statement for two different columns
[ "", "mysql", "sql", "" ]
In a certain table, I'm trying to get the `CCID`s that have rows with a `TypeID`, and no rows of any other `TypeID`. The following SQL query seems incorrect ``` SELECT T1.CCID, T1.TrCnt AS OurTypeCnt, T2.TrCnt AS NotOurTypeCnt FROM (SELECT CCID, COUNT(CCID) AS TrCnt FROM CCsTransactions W...
You access the same table twice with different WHERE-conditions. This can be replaced by CASE: ``` SELECT CCID, COUNT(CASE WHEN TypeID = 5 THEN CCID END) as OurTypeCnt, COUNT(CASE WHEN TypeID <> 5 THEN CCID END) as NotOurTypeCnt FROM CCsTransactions GROUP BY CCID HAVING ((OurTypeCnt >= 1) AND (NotOurTypeCnt < ...
You complete query can be written as: ``` select ccid from CCsTransactions group by ccid having sum(case when TypeId = 5 then 1 else 0 end) > 0 and sum(case when TypeId <> 5 then 1 else 0 end) = 0; ``` Or, a simpler way is: ``` select ccid from CCsTransactions group by ccid having max(TypeId) = 5 and min(Type...
SQL Group By COUNT in two
[ "", "sql", "sql-server", "" ]
My question here is what is the difference between `CTE` and `View` in **SQL**. I mean in which case I should use the `CTE` and which case the `View`. I know that both are some kind of virtual tables but I can't differentiate their use. I found a similar question [here](https://stackoverflow.com/questions/6026842/cte-...
Views can be indexed but CTE can't. So this is one important point. CTE work excellent on `tree hierarchy`i.e. recursive Also, consider views when dealing with complex queries. Views being a physical object on database (but does not store data physically) and can be used on multiple queries, thus provide flexibility ...
Both will be interpreted exactly the same by the Plan Optimizer. It's just a different thing. A view can be used on its own. It can encapsulate complex statements to a more simple query. Where a CTE is mostly used to write cleaner code with lesser redundancy in procedures/views for example. You can use a CTE for recu...
SQL - CTE vs VIEW
[ "", "sql", "sql-server", "common-table-expression", "sql-view", "" ]
I'm looking for a way to fire a trigger based on a condition and below is my sql. How do i include an `IF` statement in this trigger to fire if `ac_mail = '1@mail.com'` ``` CREATE TRIGGER username ON temp AFTER INSERT AS DECLARE @var1 int ,@var2 char (100) ...
try this :- ``` CREATE TRIGGER username ON temp AFTER INSERT AS DECLARE @var1 int ,@var2 char (100) Select @var1 = al_id ,@var2 = ac_mail From inserted IF @var2 = '1@mail.com' BEGIN INSERT INTO user (v_id,v_m) VALU...
Triggers can fire for *multiple* rows - so using scalar variables to capture the data is usually wrong. As is querying the base table rather than [`inserted`](https://msdn.microsoft.com/en-us/library/ms191300.aspx) - `inserted` contains just the rows that caused the trigger to fire, whereas you're querying temp for any...
Insert trigger with an IF statement
[ "", "sql", "sql-server", "" ]
I have a table in the following structure: ``` id | att1 | att2 | att3 ----------------------- 1 | a1 | b1 | c1 2 | a2 | b2 | c2 3 | a3 | b3 | c3 ``` And I want to transpose the columns to become rows for each id. Like this: ``` id | attname | value ------------------------ 1 | att1 | ...
Do `UNION ALL`: ``` select id, 'att1' as attname, att1 as value from tablename union all select id, 'att2' as attname, att2 as value from tablename union all select id, 'att3' as attname, att3 as value from tablename ``` Note that `VALUE` is a reserved word in SQL, so if that's your real column name you need to doubl...
You can use unpivot for this task. ``` SELECT * FROM table UNPIVOT ( value FOR att_name IN (att1 as 'att1', att2 as 'att2', att3 as 'att3') ); ```
SQL query transposing columns
[ "", "sql", "oracle11g", "" ]
I have a schema with four tables Users, Groups, Memberships & MembershipControls Memberships is a M:M between users & groups. Membership controls specify the groups that a user must already be a member of to be a member of a group. For example to be a member of the "Green" group a user must already be a member of ei...
The sub query identifies the groups the user is entitled to be a member of and the parent query identifies the groups the user is currently a member of. When this query is run against the fiddle above it identifies no records for deletion from memberships. If the middle two rows are removed from the memberships table ...
Try: ``` delete from memberships where user_id in ( select user_id from memberships group by user_id having sum(case when group_id = 4 then 1 else 0 end) = 1 and sum(case when group_id = 2 then 1 else 0 end) = 0 and sum(case when group_id = 3 then 1 else 0 end) = 0 )...
SQL self referencing query
[ "", "sql", "activerecord", "" ]
I am pulling my hair out trying to create a running / cumulative `median` of a partitioned value, in a chronological ordering. Basically I have a table: ``` create table "SomeData" ( ClientId INT, SomeData DECIMAL(10,2), SomeDate TIMESTAMP ); ``` With some data: ``` INSERT INTO "SomeData" (ClientId, Some...
I wonder if you can do this with `nth_value()`: ``` SELECT ClientId, SomeDate, NTH_VALUE(seqnum / 2) OVER (PARTITION BY ClientId ORDER BY SomeDate) FROM (SELECT s.*, COUNT(*) OVER (PARTITION BY ClientId ORDER BY SomeDate) as seqnum FROM SomeData s ) s ORDER BY ClientId, SomeDate; ``` As...
I think the solution presented by @GordonLinoff is not correct because it does not order the rows with the value you are trying to find median of. The correct way inspired by : [Moving Median, Mode in T-SQL](https://stackoverflow.com/questions/29542846/moving-median-mode-in-t-sql) works on redshift: ``` WITH CTE AS ...
How can I achieve a windowed running median in Redshift?
[ "", "sql", "amazon-redshift", "" ]
While removing duplicate rows with same ID value, how to remove the rows that has null value in one particular column. Note: there are other non-duplicate rows (below e.g., 12) that has NULL value and should still get selected in the result set. Input table: ``` Id | sale_date | price -----------------------------...
Assuming you have SQL Server 2008 or above, this will work for you. I use row\_number and assign the values by ID starting at the max date. So any value higher than 1 is lower than the max date for that particular ID so I delete row\_num greater than 1. Check it out: ``` DECLARE @yourTable TABLE (ID INT,Sale_date DAT...
Try this ``` SELECT * FROM ( SELECT *, ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Sale_Date desc) AS ROW_NUM FROM AA1) A WHERE ROW_NUM<2 ```
How to remove duplicate ID rows. While removing, use the rows that has NULL value in another column
[ "", "sql", "sql-server", "t-sql", "" ]
I've tried flexing my Google-fu to no avail so here I am! Unfortunately I cannot change anything about these tables as they are coming out of an application that I have to report out of. In SQL Server 2008, I'm trying to replace multiple values in one text string column (Table 1) with the value from another table (Tab...
I'm sorry for this solution in advance :) It does what you need though: ``` create table TableA( id int, string varchar(255) ) create table table2( id varchar , text varchar(255) ) insert into tableA values(1,'a,b,c,d') insert into tableA values(2,'e,f') insert into table2 values('a', 'value1') insert into table2 ...
This site has a delimited text split function <http://www.sqlservercentral.com/articles/Tally+Table/72993/> Use that function to split your values out into a temp table. Replace the values in your temp table with the new values. Then use `STUFF..FOR XML` to combine the records back together and update your table. One...
SQL Server 2008 - Replace Text Values in Column with Values from Another Table
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have a simple question related to grouping rows by date with some "narrative" periods. Let's assume that I have very simple table with articles. ID which is PK, title and date. The date column is datetime / timestamp. I would like to group somehow my results so I can present them in the view like **Written today:**...
Gordon should have credit for writing this out. But I think you probably just want to append a column with the appropriate descriptor and probably sort them in the order you'd like to see them. ``` select title, case when date = curdate() then 'today' when date >= curdate() - interval 6 day then 'last...
You can use a `case` statement for the grouping column. Something like this: ``` select (case when date = curdate() then 'today' when date >= curdate() - interval 6 day then 'last 7 days' when date >= curdate() - interval 29 day then 'last 30 days' else 'older' end), ...
Group query results by "today", "in last 7 days", "in last month" and "older"
[ "", "mysql", "sql", "database", "group-by", "" ]
I am trying to join two tables and only select the dealers that did not have their promo code used on any order. How can I do this? I'm trying this below, but it's not working right. In the example I want to get just Bob, since his `promo_code` hasn't been used in any orders. ``` SELECT d.`name` FROM z_dealer d LEFT...
``` SELECT d.`name` FROM z_dealer d LEFT JOIN z_order o ON (d.promo_code = o.promo_code) WHERE o.promo_code IS NULL ``` ![SQL JOINS](https://i.stack.imgur.com/W4eNX.png)
Have you tried `INNER JOIN`? or You can try `IN` like this : ``` SELECT d.name FROM z_dealer d WHERE d.promo_code not in( SELECT promo_code FROM z_order) ```
How do I select all the dealers that did not have an order?
[ "", "mysql", "sql", "" ]
I have a call in SQL Server 2012 that I need to have working on Server 2005 and 2008. `FORMAT(Date, 'yyyyMM') = 201501` is what I am currently using and need to use DATEPART older versions of SQL Server but cannot see a way of doing it easily. Any help would be very much appreciated.
Earlier versions of SQL Server don't have the `FORMAT`, so you'd need to so something like ``` YEAR(Date) = 2015 AND MONTH(Date) = 1 ``` or something like that to check the two conditions
Should work with SQL Server 2005 and 2008 ``` DECLARE @Date DATETIME = GETDATE(); SELECT CAST(YEAR(@Date) AS VARCHAR(4)) + RIGHT('00' + CAST(MONTH(@Date) AS VARCHAR(2)),2) RESULT: 201606 ``` If you are going to use it in where clause you can do something like... ``` WHERE YEAR(DateColumn) = 2016 AND MO...
SQL Server DATEPART for year and month
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I am going to perform a table-wide update on a huge table (+200Millon records) so I am going to populate the data via SELECT into a separate table, than drop the original and rename the new one. [In one of the articles](https://stackoverflow.com/questions/3711217/fastest-way-to-update-120-million-records) someone ment...
Based on your edited answer the quickest way to do that is: * If you have to include default value to the column `ALTER TABLE {TABLENAME} ADD {COLUMNNAME} {TYPE} {NULL|NOT NULL} CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE} [WITH VALUES]` and then drop the old column from the table. ``` ALTER TABLE {...
By the way, I would suggest that you WON'T populate the table by using `SELECT * INTO`. This will lock your source table for everyone else during the insertion, which could take quite a time. Just a suggestion, try this instead: ``` SELECT TOP 0 INTO [newTable] FROM [oldTable] INSERT INTO [newTable] SELECT * FROM [o...
Rename table via sp_rename or ALTER SCHEMA
[ "", "sql", "sql-server", "sql-server-2012", "" ]