Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Let's say, for example, I have a list of email addresses retrieved like so: ``` SELECT email FROM users ORDER BY email ``` This returns: ``` a@email.com b@email.com c@email.com ... x@email.com y@email.com z@email.com ``` I'd like to take this result set, slice the bottom 3 emails and move them to the top, so you'd ...
If you know the values are "x" or greater, you can simply do: ``` order by (case when email >= 'x@email.com' then 1 else 2 end), email ``` Otherwise, you can use `row_number()`: ``` select email from (select email, row_number() over (order by email desc) as seqnum from users u ) u order by (case ...
Assuming `email` is defined `UNIQUE NOT NULL`. Else you need to do more. ``` SELECT email FROM (SELECT email, row_number() OVER (ORDER BY email DESC) AS rn FROM users) sub ORDER BY (rn > 3), rn DESC; ``` In Postgres you can just sort by a `boolean` expression. `FALSE` sorts before `TRUE`. More: * [Sorting null val...
PostgreSQL - Slice the bottom N results and move them to the top
[ "", "sql", "postgresql", "sql-order-by", "" ]
Hi and thanks in advance. I have a few case statements that calculate "Quantity" based on the text in "ProductName." ``` Productname Quantity Product1 - 5 pack should = 5 Product2 - 10 pack should = 10 Product3 - 25 pack should = 25 ``` My case works well, however, when I do th...
Case expression are searched in order. Put the more restrictive ones first. Or if all the names fit the pattern you describe then this will probably work. ``` select cast(left(right(ProductName, 7), 2) as int) as Quantity from ... ``` Or you could use `substring` with a negative start position potentially. ``` cast...
Depending on your data, you could use LIKE '%[ -]5 pack'. (Notice that inside the brackets is a space and a hyphen.) This keeps you from having to order the case statement correctly.
SQL Like ending in specific string %5% vs. %25%
[ "", "sql", "" ]
I have a following query: ``` SELECT COUNT (*) AS Total, Program, Status FROM APP_PGM_CHOICE WHERE Program IN ( 'EX', 'IM') AND APP_PGM_REQ_DT >= '20150101' AND APP_PGM_REQ_DT <= '20150131' AND Status IN ( 'PE','DN','AP') GROUP BY Program, Status ORDER BY Program, Status ``` And the output is: ``` Total Prog...
Yes you could do it this way: ``` Select T1.Total Total1, T1.Program Program1, T2.Total Total2, T2.Program Program2, T1.Status From (SELECT COUNT (*) AS Total, Program, Status FROM APP_PGM_CHOICE WHERE Program = 'EX' AND APP_PGM_REQ_DT >= '20150101' AND APP_PGM_REQ_DT <= '20150131' AND Status IN ( 'PE','DN','AP')...
You can do this with a UNION query and some simple selects ``` SELECT GROUP_CONCAT(total1) as total1, GROUP_CONCAT(proram1) as program1, GROUP_CONCAT(total2) as total2, GROUP_CONCAT(program2) as program2 FROM (SELECT total AS total1, program AS program1, null AS total2, null AS program2 WHERE program = 'EX' UNION SEL...
How to divide SQL/MySQL query output into multiple tables?
[ "", "mysql", "sql", "" ]
I do not understand why I get an error saying "Unknown column 'cyclist.ISO\_id' in 'where clause'" ``` SELECT name, gender, height, weight FROM Cyclist LEFT JOIN Country ON Cyclist.ISO_id = Country.ISO_id WHERE cyclist.ISO_id = 'gbr%'; ```
It looks like your table name is `Cyclist`, not `cyclist` - capital `C`. In your `WHERE` clause your're therefore referencing the column of a table which does not exist.
From the [docs](http://dev.mysql.com/doc/refman/5.7/en/identifier-case-sensitivity.html) (with my emphasis): > Although database, table, and trigger names are not case sensitive on > some platforms, **you should not refer to one of these using different > cases within the same statement**. The following statement woul...
Why does my SQL statement show unknown column in WHERE clause
[ "", "mysql", "sql", "" ]
So first I would like to preface this question by letting everyone know I am pretty new to sql and coding in general. I have a query: ``` Select Distinct [t1].[Name] AS Subdivision , [t2].[Description] AS SubStatus , [t4].[Name] AS ConnectingSubName , [t2].[Description] As ConnectingSubStatus , [t5].[ActualPublic...
You want to use `row_number()`. Something like this: ``` with t as ( Select [t1].[Name] AS Subdivision, [t2].[Description] AS SubStatus, [t4].[Name] AS ConnectingSubName, [t2].[Description] As ConnectingSubStatus, [t5].[ActualPublicationEndDate], [t5].[version] as Version From [Pt...
The problem in your query is `ActualPublicationEndDate` column in `group by` you need to remove it from `group by` and `select` list Instead you can use `Row_Number` to find the max `version` per `Subdivision, SubStatus, ConnectingSubName and ConnectingSubStatus`. ``` Select * from ( select *, row_number() ov...
SQL MAX() Function returning All Results
[ "", "sql", "sql-server", "sql-server-2012", "greatest-n-per-group", "" ]
I am trying to return all instances in a Customers table where the statustype= 'dc' then for those results, the count on FC is > 1 and the Count on Address1 is 1. IE: ``` FC Address1 111 abc 111 cde 432 qqq 432 qqq ``` I need the 111 FC results back because their address1 is different. But I don't nee...
If you want the details about the FCs that have more than one unique address then this query will give you that: ``` select c.* from customers c join ( select FC from customers where statustype = 'dc' group by fc having count(distinct Address1) > 1 ) a on c.FC = a.FC ```
Try using `Distinct COUNT` ``` SELECT * FROM Customers WHERE FC IN(SELECT FC FROM Customers WHERE StatusType = 'dc' GROUP BY FC HAVING Count(DISTINCT Address1) > 1) ORDER BY FC, Address1 ```
Select where Count of 1 field is greater than a value and count of another is less than a value
[ "", "sql", "count", "group-by", "" ]
This may be simple, but I cannot figure out the correct and simplest way to query a table which contains a date col to return the rows in which the date belongs to the current academic year. Knowing that for academic year I mean the period from the 1st of September of a year to the 31st of august of the next one, how ...
This is an Oracle equivalent of Andomar's post - ``` select * from dts where case when extract (month from dt) < 9 then extract (year from dt) - 1 else extract (year from dt) end = extract (year from sysdate) ``` **Fiddle:** <http://sqlfiddle.com/#!4/75a16/1/0>
You could use a `case` to convert a date to its academic year. For SQL Server, that could look like: ``` select * from YourTable where case when month(DateColumn) < 9 then year(DateColumn) - 1 else year(DateColumn) end = year(getdate()) ```
How can a query select dates from only a specific academic year?
[ "", "sql", "oracle", "" ]
For Example, I have table like this: ``` Date | Id | Total ----------------------- 2014-01-08 1 15 2014-01-09 3 24 2014-02-04 3 24 2014-03-15 1 15 2015-01-03 1 20 2015-02-24 2 10 2015-03-02 2 16 2015-03-03 5 28 2015-03-09 5 28 ``` I want the output to be: ``` Date | Id |...
You can use `left join` as ``` select t1.* from table_name t1 left join table_name t2 on t1.Id = t2.Id and t1.Date >t2.Date where t2.Id is null ``` <http://dev.mysql.com/doc/refman/5.0/en/example-maximum-column-group-row.html>
You can also use Max() in sql: ``` SELECT date, id, total FROM table as a WHERE date = (SELECT MAX(date) FROM table as b WHERE a.id = b.id ) ```
how to get latest record or record with max corresponding date of all distinct values in a column in mysql?
[ "", "mysql", "sql", "" ]
I have a table `Reviews` with columns `MovieID` and `Rating`. In this table, Ratings are associated to a particular MovieID. For example, MovieID 123 can have 500 ratings, ranging from 1-5. I want to display N-Top movies, with the highest average rating(rounded to 4 decimals) on the top, in the format: ``` movieID|...
It's not the correct way to do it. When you use aggregate function like `avg()` you need to include a `group by` clause that determines over what item the function should be applied. In your case you should do ``` SELECT TOP 5 MovieID, ROUND(AVG(CAST(Rating AS FLOAT)), 4) as avg FROM Reviews GROUP BY MovieID ORDE...
Here is query which will solve your problem: ``` SELECT MovieID, ROUND(AVG(rating),4) AS avg FROM your_table GROUP BY MovieID ORDER BY ROUND(AVG(rating),4) DESC LIMIT 4 ``` Here I have taken `N = 4` as in your sample output from above. Also, you will need to replace `your_table` in this query with the actual name of ...
Order a column by average sql
[ "", "sql", "sql-server", "" ]
``` SELECT user.username, offer.* FROM offer INNER JOIN user ON user.userid = offer.userid WHERE offer.date BETWEEN (NOW() - INTERVAL 40 DAY) AND NOW() ``` This work fine. It display record with in 40 days time interval, With current day/date as ref. **Problem:** I want to get records 40 or more days old with la...
In this case you can do this: ``` SELECT user.username, offer.* FROM offer INNER JOIN user ON user.userid = offer.userid WHERE offer.date < (NOW() - INTERVAL 40 DAY) ``` You was pretty close to doing ;-)
``` SELECT user.username, offer.* FROM offer INNER JOIN user ON user.userid = offer.userid WHERE offer.date < (NOW() - INTERVAL 40 DAY) ```
How get values from database one month old ignoring certain days from current date?
[ "", "mysql", "sql", "database", "date", "select", "" ]
``` delete from tx_table where buyer_id in(select t.buyer_id from tx_table t left join user_table u on t.buyer_id=u.user_id where u.user_id is null) ``` I am getting erro...
Try this: ``` DELETE FROM tx_table WHERE buyer_id IN ( SELECT buyer_id FROM ( SELECT DISTINCT t.buyer_id AS buyer_id FROM tx_table LEFT JOIN user_table u on t.buyer_id=u.user_id where u.user_id is null ) AS c ) ```
Maybe the sql sentence is wrong. Do: ``` $delete = delete from tx_table where buyer_id in(select t.buyer_id from tx_table t left join user_table u on t.buyer_id=u.user_id ...
Error in mysql delete query
[ "", "mysql", "sql", "" ]
I have a stored procedure as below. Please note this is an example only and the actual query is long and has many columns. ``` select *, (select field_1 from table_1 where field1='xx' and disty_name = @disty_name) as field_1, (select field_2 from table_2 where field1='xx' and disty_name = @disty_name) as ...
I think I found the answer.. Step 1 - make the parameter optional in the SP @disty\_name ncarchar(40) = null and then in the query ``` select *, (select field_1 from table_1 where field1='xx' and (@disty is null or dist_name=@disty)) as field_1, (select field_2 from table_2 where field1='xx' and (@disty is null or...
``` Set @disty_name = NULLIF(@disty_name, 'All') select *, (select field_1 from table_1 where field1='xx' and disty_name = coalesce(@disty_name,disty_name)) as field_1, (select field_2 from table_2 where field1='xx' and disty_name = coalesce(@disty_name,disty_name)) as field_2, from table_xx where disty_name=coalesce(...
SQL Server : Where condition based on the parameters
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
So the task is: Find the youngest sailor in each rating level - My tables: ``` Sailors(sid : integer, sname : string, rating : integer, age : real) Reserves(sid : integer, bid : integer, day : date) Boats(bid : integer, bname : string, color : string) ``` - Is something like this even possible: ``` select min(a...
``` select rating,sid,age from Sailors as S where (age,rating) in ( select min(age),rating from Sailors group by rating ) ``` **EDIT :** You could just do `select rating,min(age) from sailors group by rating;` to get the minimum age in the rating level but you won't get the details of the sailo...
``` SELECT rating, MIN(age) FROM Sailors GROUP BY rating; ``` See the MySQL documentation on [aggregate functions](http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html).
how to increase a search variable by 1 in sql query
[ "", "mysql", "sql", "" ]
I'm trying to find some SQL code and having it doesn't seem to be returning my desired output. Here is my create/insert statement ``` CREATE TABLE temp ([screenName] varchar(130), [realName] varchar(57)) ; INSERT INTO temp ([screenName], [realName]) VALUES ('WillyWonka', 'Will Stinson'), ('Barbara Sm...
Use `LIKE` operator. ``` SELECT * FROM temp WHERE realName LIKE '% S_i%' ```
do you want ``` SELECT LEFT(realName,CHARINDEX(' ',realName)-1) FROM temp Where realName like '% S_i%' ``` [wildcard single character](https://msdn.microsoft.com/en-us/library/ms174424.aspx)
Looking for a particular substring in SQL string
[ "", "sql", "substring", "space", "charindex", "" ]
**SCENARIO** I want to design tables for saving Data of ***Cattle*** and ***Calfs***. **Attributes/columns Common among Cattle and Calf** * Price * Birth Date etc. (Some coming from FK as well like Breed etc) **Attributes reserved for Calf** * Father * Mother **Attributes reserved for CATTLE (Female)** * IsMil...
Question is too broad and many possible answer, but I tried to since I'm into database designing. It's not perfect but I hope it can help you a little. Calf Table (Calf records) ![enter image description here](https://i.stack.imgur.com/HmlzY.png) Relationships to Cattle 2x ![enter image description here](https://i...
I think one table for the animal with a self-relationship for father and mother is the way to go. Something like this; ``` CREATE TABLE [dbo].[Animal]( [AnimalID] [int] IDENTITY(1,1) NOT NULL, [Sex] [char](1) NOT NULL CONSTRAINT [Animal_Sex] CHECK (([Sex]='F' OR [Sex]='M')), [Name] [varchar](100) NOT NULL...
Database Design Issue - Different Statuses for Different Sex
[ "", "sql", "sql-server", "database", "database-design", "" ]
Say I have two tables like so: `fruits` | id | name | | --- | --- | | 1 | Apple | | 2 | Orange | | 3 | Pear | `users` | id | name | fruit | | --- | --- | --- | | 1 | John | 3 | | 2 | Bob | 2 | | 3 | Adam | 1 | I would like to query both of those tables and in the result get user ID, his name and a fruit name (frui...
You need to `JOIN` the fruit table like this: ``` SELECT u.id, u.name, f.name FROM users u JOIN fruits f ON u.fruit = f.id ``` See a working example [**here**](http://sqlfiddle.com/#!5/79438/2)
``` select a.id,a.name,b.name as fruit from users a join friuts b on b.id=a.fruit ```
Query two tables and replace values from one table in the second one
[ "", "mysql", "sql", "" ]
How would I query the range of a number column if the number ends somewhere then picks up again at a higher number? If I had a column like: ``` Number ------- 1 2 3 4 5 11 12 13 ``` How can I return a result like ``` Min | Max ---------- 1 | 5 11 | 13 ```
``` ;WITH CTE AS ( SELECT Number, Number - dense_rank() over (order by Number) grp FROM yourtable ) SELECT min(Number) min, max(Number) max FROM CTE GROUP BY grp ``` [FIDDLE](http://sqlfiddle.com/#!6/27c24/1)
Another approach: ``` select n1.number as min,min(n2.number) as max from table n1 JOIN table n2 ON n1.number<n2.number AND NOT EXISTS (select 1 from number where number = n1.number-1) AND NOT EXISTS (select 1 from number where number=n2.number+1) group by n1.number order by n1.number ```
getting the range of a number column(min/max) if there are missing numbers in between
[ "", "sql", "sql-server", "sql-server-2005", "" ]
I am trying to pull the memberinstance from a table based on the max DateEnd. If it is Null I want to pull that as it would be still ongoing. I am using sql server. select memberinstanceid from table group by memberid having MAX(ISNULL(date\_end, '2099-12-31')) This query above doesnt work for me. ...
I think you need something like the following: ``` select MemberID, MemberInstanceID from table t where ( -- DateEnd is null... DateEnd is null or ( -- ...or pick the latest DateEnd for this member... DateEnd = ( select max(DateEnd) from table where Membe...
You have a good start but you don't need to perform any explicit grouping. What you want is the row where the EndDate is null or is the largest value (latest date) of all the records with the same MemberID. You also realized that the Max couldn't return the latest non-null date because the null, if one exists, must be ...
Select most recent InstanceID base on max end date
[ "", "sql", "" ]
I'm having trouble figuring out how to return a query result where I have row values that I want to turn into columns. In short, here is an example of my current schema in SQL Server 2008: > ![enter image description here](https://i.stack.imgur.com/5amSe.png) And here is an example of what I would like the query res...
There are many different ways that you can get the result. Multiple JOINs, unpivot/pivot or CASE with aggregate. They all have pros and cons, so you'll need to decide what will work best for your situation. Multiple Joins - now you've stated that you will always have 2 rows for each day - one for apple and orange. Wh...
Given your criteria, joining the two companion rows together and selecting out the appropriate fields seems like the simplest answer. You could go the route of PIVOTs, UNIONs and GROUP BYs, etc., but that seems like overkill. ``` select apples.Timestamp , apples.[NumOffered] as ApplesNumOffered , apple...
SQL query for returning row values as columns - SQL Server 2008
[ "", "sql", "sql-server", "sql-server-2008", "" ]
This query could return the wrong name, because the names I want to query are the ones of the smallest animals of each species. How could I get the right `a.name` ``` SELECT a.name, MIN(a.size) FROM animal a LEFT JOIN species s ON s.idSpecies = a.idAnimal GROUP BY s.id ```
One approach for this, is to first find the smallest size of animal per species (as you have done), although I am assuming that species can never be null since an animal must belong to a species, it also does not require a join to species at this point: ``` SELECT a.IDSpecies, MIN(a.Size) AS Size FROM Animal AS a ...
Following the simple example of Group By : ``` SELECT C.CountryName Country, SN.StateName, COUNT(CN.ID) CityCount FROM Table_StatesName SN JOIN Table_Countries C ON C.ID = SN.CountryID JOIN Table_CityName CN ON CN.StateID = SN.ID GROUP BY C.CountryName, SN.StateName ORDER BY SN.StateName ``` OUTPUT : ``` Countr...
How to get multiple fields from one criteria using SQL group by?
[ "", "sql", "mysqli", "" ]
We have a table in MySql with arround 30 million records, the following is table structure ``` CREATE TABLE `campaign_logs` ( `domain` varchar(50) DEFAULT NULL, `campaign_id` varchar(50) DEFAULT NULL, `subscriber_id` varchar(50) DEFAULT NULL, `message` varchar(21000) DEFAULT NULL, `log_time` datetime DEFAULT...
If the query without the `count(distinct)` is going much faster, perhaps you can do nested aggregation: ``` SELECT log_type, log_date, count(*) AS COUNT, sum(cnt) AS total FROM (SELECT log_type, DATE_FORMAT(CONVERT_TZ(log_time,'+00:00','+05:30'),'%l %p') AS log_date, subscriber_id, cou...
To answer your question: > Is there a way to refactor my query, or add an index, or something, to > get the COUNT(DISTINCT...) values, but much faster? Yes, do not group by the calculated field (do not group by the result of the function). Instead, pre-calculate it, save it to the persistent column and include this p...
Optimizing COUNT(DISTINCT) slowness even with covering indexes
[ "", "mysql", "sql", "aggregate-functions", "query-performance", "mysql-variables", "" ]
I'm trying to search in an database for records with a specific date. I've tried to search in the following ways: ``` SELECT * FROM TABLE_1 WHERE CAL_DATE=01/01/2015 ``` and ``` SELECT * FROM TABLE_1 WHERE CAL_DATE='01/01/2015' ``` I'm working with an Access database, and in the table, the dates are showing in th...
Any of the options below should work: Format the date directly in your query. ``` SELECT * FROM TABLE_1 WHERE CAL_DATE=#01/01/2015#; ``` The DateValue function will convert a string to a date. ``` SELECT * FROM TABLE_1 WHERE CAL_DATE=DateValue('01/01/2015'); ``` The CDate function will convert a value to a date....
Try using CDATE function on your filter: ``` WHERE CAL_DATE = CDATE('01/01/2015') ``` This will ensure that your input is of date datatype, not a string.
Finding a Specific Date with SQL
[ "", "sql", "datetime", "ms-access", "" ]
My question is similar to this. [Check if column value exists in another column in SQL](https://stackoverflow.com/questions/21800481/check-if-column-value-exists-in-another-column-in-sql) In my case, however, there're up to five select statements in the `IN` statement. It looks something like this : `SELECT Criterio...
For Access SQL you will need to use a construct like this: ``` SELECT ... FROM tblFilter WHERE Criterion1 IN (SELECT Criterion2 FROM tblFilter) OR Criterion1 IN (SELECT Criterion3 FROM tblFilter) ```
Try this: `SELECT Criterion1 FROM tblFilter WHERE Criterion1 IN (SELECT Criterion2 FROM tblFilter UNION SELECT Criterion3 FROM tblFilte` UNION is combine together your both select stetments, but they have to return the same count of element (1 in your stetment) and same type. EDIT: Try this: `SELECT Criterion1 FROM...
SQL IN statement with multiple SELECT statements in it
[ "", "sql", "ms-access", "select", "" ]
I want to randomly select 20 rows from a large table and use the following query that works fine: ``` SELECT id FROM timeseriesentry WHERE random() < 20*1.0/12940622 ``` (12940622 is the number of rows in the table). I now want to retrieve the number of rows automatically and use ``` WITH tmp AS (SELECT COUNT(*) n F...
This is ugly, but it works. It also avoids the identifier `type`, which is an (unreserved) keyword. ``` WITH zzz AS ( SELECT ztype , COUNT(*) AS cnt FROM timeseriesentry GROUP BY ztype) SELECT * FROM timeseriesentry src WHERE random() < 20.0 / (SELECT cnt FROM zzz ...
I created a table with no numeric field: ``` create table timeseriesentry as select generate_series('2015-01-01'::timestamptz,'2015-01-02'::timestamptz,'1 second'::interval) id, 'ret'::text v ; ``` and reused window aggregation: ``` WITH tmp AS (SELECT round(count(*) over()*random()) n FROM timeseriesentry limit 20)...
Comparison with calculated value fails in PostgreSQL
[ "", "sql", "postgresql", "" ]
I've been given part of a project financial reporting system to work on. Basically, I'm trying to modify an existing query to restrict returned results by date in a field which contains a variable date format. My query is being sent the date from someone elses code in the format YYYY twice, so e.g. 2014 and 2017. In t...
I guess you could use the [**year**](https://msdn.microsoft.com/en-us/library/ms186313.aspx) system function if your date columns are any of the given [**date** or **datetime** data types available in SQL Server](https://msdn.microsoft.com/en-CA/library/ms186724.aspx). This would allow you to write something that look...
So from my understanding you have 2 parameters for the start and end years that should be used to filter results. With dates either being `YYYYMM` or `YYYYMMDD`, you can use string manipulation to take the first 4 characters and convert it to an `INT`, which can then be used to compare to the parameters. Something li...
SQL like syntax using date YYYY
[ "", "sql", "sql-server", "syntax", "sql-like", "" ]
How to set dynamic count for `GO` statement? I am getting the following error: > A fatal scripting error occurred.Incorrect syntax was encountered > while parsing Go. when I tried to run the below query: ``` Declare @count int Select @count=COUNT(*) From Users Insert Into #DummyUsers Select * from Users where Us...
If you simply want to insert a repeated row you could use a CTE or numbers table. ``` -- Sample data. declare @Users as Table ( UserId Int Identity, Name VarChar(16) ); insert into @Users ( Name ) values ( 'Bob' ), ( 'Carol' ), ( 'Ted' ), ( 'Alice' ); select * from @Users; -- Load another table with repetitions of ...
You can't. As soon as SSMS encounters GO the batch is terminated and your variable no longer exists.
How to execute the GO statement with dynamic count?
[ "", "sql", "sql-server", "database", "t-sql", "" ]
I need to strip out urls from results of a SQL query. All urls look like `http://` so no complex regex is necessary. But the urls can be anywhere in the string. Examples: ``` alpha beta http://alphabeta.com/abc gamma http://gammadel.com/def delta http://epsilo.com/ghi epsilon theta ``` How can I strip these urls fro...
What about ``` SELECT REPLACE( 'alpha gamma http://gammadel.com/def delta beta', CONCAT('http://', SUBSTRING_INDEX( SUBSTRING_INDEX('alpha gamma http://gammadel.com/def delta beta', 'http://', -1),' ', 1) ),'' ); ``` I've tested it for strings that you provided, but not sure if it meets fully your r...
As you cannot use functions like `preg_replace` without having any addons/libraries - and as you've only tagged your question with `mysql`/`sql`, you're going to need to install this to give you the ability to use a regular expression replace. <https://github.com/mysqludf/lib_mysqludf_preg#readme> Now that's installed...
How can I strip out urls from a string in MySQL?
[ "", "mysql", "sql", "" ]
I have a database table with 3 columns. I want to find all duplicates that have snuck in un-noticed and tidy them up. Table is structured approximately ``` ID ColumnA ColumnB 0 aaa bbb 1 aaa ccc 2 aaa bbb 3 xxx bbb ``` So what would my query look like ...
You can create a query that groups and counts the duplicate rows: ``` SELECT COUNT(1) , ColumnA , ColumnB FROM YourTable GROUP BY ColumnA , ColumnB HAVING COUNT(1) > 1 ``` You can then add this to a subquery to output the full rows that hold the duplicate data. Here's a full executable example based on your sam...
Use `count(*)` as a window function: ``` select t.* from (select t.*, count(*) over (partition by columna, columnb) as cnt from table t ) t where cnt > 1; ```
Find duplicates in a database table, where 2 columns are duplicated
[ "", "sql", "sql-server", "" ]
Newbie question, please forgive my ignorance :P I have a datasets with different columns. Quizzes, names, grades. Some students have not done all quizzes. I just want people who did the 8 quizzes. I put this code: ``` SELECT * FROM quiz_attempts WHERE qname like "onlinelernen_quiz_1" AND qname like "onlinelernen_q...
Your query can't work since you are asking for all the records where qname is like "onlinelernen\_quiz\_1" and, **simultaneously**, like "onlinelernen\_quiz\_2", 3 ... , which is impossible. Try this: It shows only the names of students whose name appears 8 times related to onlinelernen quizs ``` SELECT Q.stname FROM...
AND gives specific result when all condition matched. Use OR ``` SELECT * FROM quiz_attempts WHERE qname LIKE "onlinelernen_quiz_1" OR qname LIKE "onlinelernen_quiz_2" OR qname LIKE "onlinelernen_quiz_3" OR qname LIKE "onlinelernen_quiz_4" OR qname LIKE "onlinelernen_quiz_5" OR qname LIKE "online...
What is wrong with this simple sql query? it returns 0 rows
[ "", "mysql", "sql", "" ]
How to select all the columns of a table except one column? I have nearly 259 columns and I can't mention all 258 columns in the `SELECT` statement. Is there any other way to do it?
You can use this approach to get the data from all the columns except one:- 1. Insert all the data into a temporary table 2. Then drop the column which you dont want from the temporary table 3. Fetch the data from the temporary table(This will not contain the data of the removed column) 4. Drop the temporary table So...
Create a view. Yes, in the view creation statement, you will have to list each...and...every...field...by...name. Once. Then just `select * from viewname` after that.
Select all the columns of a table except one column?
[ "", "sql", "sql-server", "" ]
We have a Transact-SQL query that contains subqueries in the where section. Inner Join gives unwanted results of adding tOrderDetails fields multiple times so we resorted to the (poor performance) sub queries. It is timing out often. We need the same result but with better performance. Any suggestions? ``` SELECT sum ...
Although I think `EXISTS` may have the best performance, you might also consider the following approach. When you mention in your question that your query has "unwanted results of adding tOrderDetails fields multiple times" it's probably because you have multiple tOrderDetail records so you need to collapse them with a...
Why do you count records if you just want to know if at least one *exists* or *not exists*? ``` SELECT Sum (Cast(Replace(tOrders.TotalCharges, '$', '') AS MONEY)) AS TotalCharges FROM [ArtistShare].[dbo].tOrders WHERE tOrders.isGiftCardRedemption = 0 AND tOrders.isTestOrder = 0 AND tOr...
What is an alternative to using subqueries in this SQL query that will give us better performance?
[ "", "sql", "sql-server", "" ]
I have two table A and table B, the common column in both table is Name, I want to know what are name in Table A that is not in table B when I do: ``` Select Name from A where Name not in (Select Name from B) ``` I am sure there are 2 name in Table A that is not in table B but the result returns nothing These name...
You probably have a `NULL` name on `B`, this makes the `NOT IN` false for every row. You should use `NOT EXISTS` instead: ``` SELECT Name FROM A WHERE NOT EXISTS (SELECT 1 FROM B WHERE A.Name = B.Name) ```
Obviously it is because of NULL value on some rows in table B. You can do what you want with `EXCEPT` ``` SELECT Name FROM TableA EXCEPT SELECT Name FROM TableB ```
T-SQL query: where column not in is giving wrong result
[ "", "sql", "sql-server", "t-sql", "" ]
I have a table ``` CREATE TABLE [misc] ( [misc_id] [int] NOT NULL, [misc_group] [nvarchar](255) NOT NULL, [misc_desc] [nvarchar](255) NOT NULL ) ``` where `misc_id [int] not null` should have been `IDENTITY (1,1)` but is not and now I'm having issues With a simple form that insert into this table but sin...
You should re-create your table with the desired identity column. The following statements will get you close. SQL Server will automatically adjust the table's identity field to MAX(misc\_id) + 1 as you're migrating data. You'll obviously need to stop trying to insert misc\_id with new records. You'll want to retrieve...
Changing a int column to an identity can cause problems because by default you cannot insert a value into an identity column without use the set identity\_insert command on. So if you have existing code that inserts a value into the identity column it will fail. However its much easier to allow SQL Server to insert val...
Insert into column without having IDENTITY
[ "", "sql", "sql-server", "sql-server-2012", "" ]
what does this error mean in mysql? ER\_NO\_DEFAULT\_FOR\_FIELD – “Field doesn’t have a default value” I've found it listed here? <http://mysqlserverteam.com/improvements-to-strict-mode-in-mysql/> and got: ``` { "code": "ER_NO_DEFAULT_FOR_FIELD", "errno": 1364, "sqlState": "HY000", "index": 0 } ``` ...
Well my guess is you have a field that requires a value and has no default. So when you insert into your table, if you don't provide a valid value for it, MySQL complains. It'd be more help if you'd shown us your tables and maybe insert query as well, but take a look at your fields. If you find one that has no default...
this problem occured due to many reason 1. You have not enter value for the column in the API(as you have not set some default value for that column) if you set some default value you willnot have error as sql add that default value of model/migrations in that column without explicitly providing any data for that colu...
ER_NO_DEFAULT_FOR_FIELD in MySQL (nodejs rest request)
[ "", "mysql", "sql", "json", "node.js", "node-mysql", "" ]
How can I count non-null entries by field/column? I see several answers to count by row but can't hack how to do so for columns. Input: ``` ╔════╦════════╦════════╦════════╗ ║ id ║ field1 ║ field2 ║ field3 ║ ║ 1 ║ do ║ re ║ me ║ ║ 2 ║ fa ║ ║ so ║ ║ 3 ║ la ║ te ║ ║ ║ 4 ║ d...
Just use `count()`: ``` select count(field1), count(field2), count(field3) from table t; ``` That is what `count()` does -- it counts non-NULL values. If you have an aversion to typing out names, then use the metadata tables (typically `information_schema.columns`) to get the column names. You can generate the SQL a...
``` SELECT count(field1) as cnt ,'field1' as field from tbl where field1 IS NOT NULL UNION all SELECT count(field2) as cnt ,'field2' as field from tbl where field2 IS NOT NULL union all SELECT count(field3) as cnt ,'field3' as field from tbl where field3 IS NOT NULL ``` IF THERE ARE ONLY 3 FIXED FIELD ABOVE SQL WILL ...
MySQL COUNT NULL content by column, GROUP by column
[ "", "mysql", "sql", "count", "null", "field", "" ]
I have to check certain rows from table and check `if-else` condition for each rows TABLE: `report` COLUMNS : `sl.no`, `count`, `total_count`, `calls` Sample Data: ``` sl.no count total_count calls ----------- ----------- ----------- ----------- 1 2 6 4 2 2 ...
Use [**CASE**](https://msdn.microsoft.com/en-us/library/ms181765.aspx?f=255&MSPPError=-2147217396) expression ``` SELECT *, CASE WHEN total_count > 6 THEN 'Yes' ELSE 'N' END FROM report ```
You could use `CASE`. You can read [documentation](https://msdn.microsoft.com/en-us/library/ms181765.aspx). ``` SELECT *, CASE WHEN total_count > 6 THEN 'Y' ELSE ' N' END FROM Report ```
select rows from table and check if condition at column in sql
[ "", "sql", "sql-server", "database", "ssms", "" ]
Here is a query: ``` SELECT k.[mg_KarId] AS [mg_KarId], k.[SymKar] AS [SymKar], k.[OpiKar] AS [OpiKar], k.[Status] AS [Status], kmlg.SymLok AS Lok_GLS1, kmlk.SymLok AS Lok_KRS1, kmlw.SymLok AS Lok_WLS1 FROM dbo.[mg_vv_Kar_All] AS k WITH (NOLOCK) LEFT JOIN ( SELECT kml.SymKar, kml.SymLok FROM dbo.mg_KarMagLo...
``` SELECT k.[mg_KarId] AS [mg_KarId], k.[SymKar] AS [SymKar], k.[OpiKar] AS [OpiKar], k.[Status] AS [Status], ( SELECT TOP 1 kml.SymLok FROM dbo.mg_KarMagLok kml WHERE kml.Mag LIKE 'GLS1' AND kml ON k.SymKar = kmlg.SymKar ) , ( SELECT TOP 1 kml.SymLok FROM dbo.mg_KarMagLok kml WHERE kml.M...
If you want to solve aggregation problem, you can group your data set. Instead of using TOP keyword, write a query like this: ``` SELECT kml.SymKar, kml.SymLok FROM dbo.mg_KarMagLok kml WHERE kml.Mag LIKE 'GLS1' group by kml.SymKar, kml.SymLok ```
left join with subquery with one result
[ "", "sql", "t-sql", "subquery", "left-join", "" ]
Which is the right syntax in order to create two or more triggers in a row by executing a query with **SQL Server**? I tried the following one: ``` GO CREATE TRIGGER TRG_MyTable_UpdatedAt ON dbo.MyTable AFTER UPDATE AS UPDATE dbo.MyTable SET UpdatedAt = GETDATE() WHERE ID IN (SELECT DISTINCT ID FROM Inser...
``` CREATE TRIGGER TRG_MyTable_UpdatedAt ON dbo.MyTable AFTER UPDATE AS BEGIN UPDATE dbo.MyTable SET UpdatedAt = GETDATE() WHERE ID IN (SELECT DISTINCT ID FROM Inserted) END GO CREATE TRIGGER TRG_MyTable_CreatedAt ON dbo.MyTable AFTER INSERT AS BEGIN UPDATE dbo.MyTable SET CreatedAt = GETDATE() ...
You forgot to write `'Begin'` ``` CREATE TRIGGER TRG_MyTable_UpdatedAt ON dbo.MyTable AFTER UPDATE AS Begin UPDATE dbo.MyTable SET UpdatedAt = GETDATE() WHERE ID IN (SELECT DISTINCT ID FROM Inserted) END GO CREATE TRIGGER TRG_MyTable_CreatedAt ON dbo.MyTable AFTER INSERT AS Begin UPDATE dbo.MyTable ...
Create two or more triggers in a row by executing a query with SQL Server
[ "", "sql", "sql-server", "" ]
I have 2 tables: ``` CREATE TABLE Items (id INT, name VARCHAR(8)); CREATE TABLE Likes (item_id INT, usr VARCHAR(8), doeslike BOOLEAN); INSERT INTO Items VALUES (1, 'Pen'), (2, 'Pencil'), (3, 'Ruler'); INSERT INTO Likes VALUES (1, 'joe', TRUE ), (1, 'jill', TRUE ), (1, 'jack', FALSE), (2,...
You can use conditional aggregation for this. If you use `SUM(condition)` inside of a select statement, you'll get the number of times that condition is true. Use it like this for your table: ``` SELECT i.name, SUM(l.doeslike = true) AS likes, SUM(l.doeslike = false) AS dislikes FROM items i JOIN likes l ON l.item_id ...
<http://sqlfiddle.com/#!9/d1e0f/2> ``` SELECT Items.* , SUM(CASE WHEN Likes.doesLike THEN 1 ELSE 0 END) as likes, SUM(CASE WHEN Likes.doesLike THEN 0 ELSE 1 END) as dislikes FROM Items LEFT JOIN Likes ON Items.id = Likes.item_id GROUP BY Items.id ```
SQL: Join and Count based on condition
[ "", "mysql", "sql", "" ]
I want get date from sql server in user specified format using GETDATE() function. if i give this query ``` select GETDATE() ``` then it is displating output date in this format ``` 2015-03-17 07:29:58.377 ``` but i want output like this . ``` 2015-03-17 ``` what statement should be added with query to get the r...
Just use `convert()`: ``` select convert(varchar(10), getdate(), 121) ```
In SQL Server 2012 onward you may use FORMAT() which is a bit more intuitive than recalling style numbers. e.g. select FORMAT( GETDATE() , 'yyyy-MM-dd' ) see: <https://msdn.microsoft.com/en-AU/library/hh213505.aspx> however do note the second parameter is case sensitive * 'yyyy-MM-dd' works * 'YYYY-MM-DD' would onl...
How to get date from sql server in user specified format
[ "", "sql", "sql-server", "sql-server-2008", "" ]
Im using this: ``` SELECT * WHERE id=MAX(id) FROM history; ``` But my query is empty. I have also tried this (This one works): ``` SELECT MAX(id) AS max_id FROM history; ``` But obviusly my query only contains the max\_id key. What am I doing wrong with the first one?
You need to add another level of `select` for the `MAX`, like this: ``` SELECT * WHERE id=(SELECT MAX(id) from history) FROM history; ``` A better approach would be to order by `id` in descending order, and limit the output to a single row: ``` SELECT * FROM history ORDER BY id DESC LIMIT 1 ```
Actually most simple query to get the max value of a column in sqlite is: ``` select MAX(id) from table; ```
Sqlite get max id not working (?)
[ "", "sql", "sqlite", "select", "" ]
I'm using PostgreSQL 9.4 with a table `teams` containing a `jsonb` column named `json`. I am looking for a query where I can get all teams which have the Players `3`, `4` and `7` in their array of players. The table contains two rows with the following `json` data: First row: ``` { "id": 1, "name": "foobar",...
You are facing two non-trivial tasks at once. * Process `jsonb` with a complex nested structure. * Run the equivalent of a relational division query on the document type. First `jsonb_populate_recordset()` works with a registered row type. Can be the row type of any (temp) table or view, or a composite type explicitl...
I wanted to do the same as above. Only other condition was I had to do substring matching and not an exact matching. This is what I ended up doing(inspired from the answer above of course) ``` SELECT t.json->>'name' AS feature_name, f.features::text FROM teams t , LATERAL ( SELECT * FROM json_populate_record...
jsonb query with nested objects in an array
[ "", "sql", "postgresql", "relational-division", "postgresql-9.4", "jsonb", "" ]
I can do the same query in two ways as following, will #1 be more efficient as we don't have join? # 1 ``` select table1.* from table1 inner join table2 on table1.key = table2.key where table2.id = 1 ``` # 2 ``` select * from table1 where key = (select key from table2 where id=1) ```
These are doing two different things. The second will return an error if more than one row is returned by the subquery. In practice, my guess is that you have an index on `table2(id)` or `table2(id, key)`, and that `id` is unique in `table2`. In that case, both should be doing index lookups and the performance should ...
MS SQL Server is smart enough to understand that it is the same action in such a simple query. However if you have more than 1 record in subquery then you'll probably use IN. In is slow operation and it will never work faster than JOIN. It can be the same but never faster. The best option for your case is to use EXISTS...
Performance of join vs pre-select on MsSQL
[ "", "sql", "sql-server", "performance", "" ]
I want to have the last column cumulative based on `ROW_ID` that resets every time it starts again with '1'. Initially my table doesn't have the `ROW_ID`, this was created using partition so at least I can segregate my records. It should add the Amt + CumulativeSum (except for the first record) all the way down and r...
try this ``` declare @tb table(ID int, [ROW-ID] int, Amt money) insert into @tb(ID, [ROW-ID], Amt) values (1,1,2), (2,2,4), (3,3,6), (4,1,2), (5,2,4), (7,4,8), (8,5,10), (9,1,2), (10,2,4), (11,3,6), (12,4,8) select *,sum(a...
The idea is to create partitions from `R` column. First leave `1` if `R = 1`, else put `0`. Then cumulative sum on that column. When you have partitions you can finally calculate cumulative sums on `S` column in those partitions: ``` --- --- --- | 1 | | 1 | | 1 | | 2 | | 0 | ...
SQL Server 2008 Cumulative Sum that resets value
[ "", "sql", "sql-server-2008", "" ]
As the title says, I am trying to `INNER JOIN` on columns that have different values/data types. In one database table, let's call it Table A I want to do a select statement to get the values of a few columns (Subject, Name, Description, Date). Though I also want a relation name. The problem is however that the relati...
To escape from the convertion error remove the first characters in `RelationID` using `Substring` then `convert` the `RelationID` to `INT` then `JOIN` with the `ID` column in `tableA` ``` SELECT TableA.subject, TableA.Name, TableA.Description, TableA.Date, TableB.RelationName FROM tableA ...
> Do a LIKE statement in the query where the ID of table B (1001 > integer) partly matches the RelationID of table A (D0001001 string). > This however didnt worked. Try the other way round: ``` SELECT TableA.Subject, TableA.Name, TableA.Description, TableA.Date, TableB.RelationName FR...
Is it possible to INNER JOIN 2 id's of a different type/values?
[ "", "sql", "sql-server", "join", "inner-join", "" ]
Need a Select Query for the following scenario, using Microsoft SQL Server 2008 ``` Order Customer Order_Type 1 A NULL 2 A NULL 3 B S 4 C NULL 5 D S 6 B NULL ``` I want to Group Customer who have placed Order Type S, So the output I am expecting is ``...
Try this out: ``` SELECT * FROM CustomerOrder ORDER BY COUNT(CASE WHEN Order_Type = 'S' THEN 1 END) OVER (PARTITION BY Customer) DESC, Customer ``` I assume you basically want to order your data, placing on top groups of customers having at least one 'S'. [**SQL Fiddle Demo**](http://sqlfiddle.com/#!...
`GROUP BY` is for grouping multiple rows together into a single row, based on a common column value. For instance, you might get a count of how many orders a particular customer has made like so: ``` SELECT Customer, COUNT(*) FROM Table GROUP BY Customer ``` That would get you output listing the customer name and th...
Order By Having Certain Value
[ "", "sql", "sql-server-2008", "" ]
I need to use [WEEK](http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_week) function so I need a **date** type. While what I have in db is a **int** type like 20150101 representing 1st,Jan 2015. I tried `FROM_UNIXTIME` but obviously it is not I want: ``` select FROM_UNIXTIME(20150101) fro...
You can just select it as a `date()` and it converts automatically. ``` SELECT DATE(20150101) FROM dual; ```
`20150101` is not a unix timestamp its in the format `ymd` you need `date_format` to format it ``` mysql> select date_format('20150101','%Y-%m-%d') as date ; +------------+ | date | +------------+ | 2015-01-01 | +------------+ 1 row in set (0.00 sec) mysql> select unix_timestamp('2015-01-01'); +---------------...
Convert yyyymmdd(int type) to date
[ "", "mysql", "sql", "" ]
I'd like to generate the following output using SQL Server 2012: ``` <parent> <item>1</item> <item>2</item> <item>3</item> </parent> ``` From three different columns in the same table (we'll call them col1, col2, and col3). I'm trying to use this query: ``` SELECT t.col1 as 'item' ,t.col2 as 'item' ,t.co...
Add a column with NULL as value to generate a separate item node for each column. ``` SELECT t.col1 as 'item' ,NULL ,t.col2 as 'item' ,NULL ,t.col3 as 'item' FROM dbo.tbl as t FOR XML PATH('parent'), TYPE; ``` Result: ``` <parent> <item>1</item> <item>2</item> <item>3</item> </parent> ``` [SQL Fiddle...
Ok, you can't use path for that. Use explicit, instead, ``` SELECT 1 AS tag,NULL AS parent, t.col1 AS [Parent!1!Item!element], t.col2 AS [Parent!1!Item!element], t.col3 AS [Parent!1!Item!element] FROM tbl t FOR XML EXPLICIT ```
SQL Server FOR XML Path make repeating nodes
[ "", "sql", "sql-server", "xml", "t-sql", "" ]
could someone help me to join 2 queries into one? Basically it's the same query with different clauses (please notice the FIELD3 filters and related counters into the subquery): ``` SELECT A.FIELD1,A.FIELD2,A.FIELD3 FROM TABLE A INNER JOIN ( SELECT FIELD1, COUNT(1) FROM TABLE where SUBSTR(F...
Combining the two queries is easy enough. Two suggestions, though. First, use a CTE rather than inline view. It doesn't change the performance -- it just looks...cleaner, less cluttered (imho). Second, if you're going to combine two queries like this, add a field that identifies each row with the reason it is there. Ma...
You should be able to use analytic functions for this. ``` SELECT field1, field2, field3 FROM (SELECT t.*, SUM(CASE WHEN field3 LIKE '33377%' THEN 1 ELSE 0 END) OVER (PARTITION BY field1) as cnthave, SUM(CASE WHEN field3 NOT LIKE '33377%' THEN 1 ELSE 0 END) OVER (PARTITION BY field1) as cntno...
Join 2 SQL queries into one
[ "", "sql", "oracle", "oracle11g", "" ]
How to do a count including not existing records, which should have '0' as the count? Here is my table: ``` CREATE TABLE SURVEY (year CHAR(4), cust CHAR(2)); INSERT INTO SURVEY VALUES ('2011', 'AZ'); INSERT INTO SURVEY VALUES ('2011', 'CO'); INSERT INTO SURVEY VALUES ('2012', 'ME'); INSERT INTO SURVEY VALUES ('2014'...
It sounds like you want a count for every cust x year combination with a zero when no survey record exists. If this is the case you will need two more tables: customers and years then do something like: ``` select leftside.cust, leftside.year, count(survey.cust) from (select * from customers, years) as leftside le...
If you have domain tables as others said, well and good. If you have to depend only on data in your table, the below query will do that for you. ``` select cp.cust, cp.year, iif(isnull(sum(cnt)), 0, sum(cnt)) as count from (select * from ( (select distinct cust from survey) as c cross join (select distinct year from...
How to do a count including not existing records?
[ "", "sql", "ms-access", "" ]
I have 3 tables in SQL Server 2008 like this: Table 1 with these columns: ``` [pod] [varchar](50) NOT NULL, primarykey [origin] [varchar](100) NOT NULL, [destination] [varchar](100) NOT NULL, [town] [varchar](50) NOT NULL, ``` Table 2 with these columns: ``` [town_id] [int] NOT NULL, primary key [town] [varchar](50...
Not sure exactly what you want, but at a guess it sounds like you want to get the 4 columns from table 1 and the 'area' column from the 3rd table using the 2nd table as a way of joining the 2. If that's the case this should work: ``` SELECT tb1.pod, tb1.origin, tb1.destination, tb1.town, tb3.area FROM Table1 as tb1 JO...
**Try below query :** ``` select POD, origin, destination , table1.town , area from Table1 inner join table2 on table2.town=table1.town inner join Table3 on table2.town_id=table3.town_id ```
How to get values from three different tables in SQL Server with primary key and without?
[ "", "sql", "sql-server", "sql-server-2008", "" ]
By running this SELECT query: ``` SELECT wp_posts.ID, wp_postmeta.meta_key, wp_postmeta.meta_value FROM wp_posts INNER JOIN wp_postmeta ON wp_posts.ID = wp_postmeta.post_id WHERE wp_posts.post_status = 'publish' AND wp_posts.post_type = 'my_post_type' AND wp_posts.post_date < NOW() AND wp_postmeta.meta_key = 'wpcf-la...
For a known set of `meta_key` you can use the following query ``` select wp.ID, max( case when pm.meta_key = 'wpcf-lat' then pm.meta_value end ) as `meta_value`, max( case when pm.meta_key = 'wpcf-long' then pm.meta_value end ) as `wpcf-long` from wp_posts wp join wp_postmeta pm on pm.post_id = wp.ID group ...
A simple `while` or `foreach` in your PHP code is the easiest way to put the data in the format you need: ``` $query = '...'; $resultset = $DB->query($query); $list = array(); while ($row = $resultset->fetchArray()) { // Check if the entry having this ID was created before $id = $row['id']; if (! isset($l...
SQL - How to concatenate this table?
[ "", "mysql", "sql", "concatenation", "" ]
I'm trying to append two tables in MS Access at the moment. This is my SQL View of my Query at the moment: ``` INSERT INTO MainTable SELECT FROM Table1 INNER JOIN Table2 ON Table1.University = Table2.University; ``` Where "University" is the only field name that *would* have similarities between the two tables. When...
You must select something from your select statement. ``` INSERT INTO MainTable SELECT col1, col2 FROM Table1 INNER JOIN Table2 ON Table1.University = Table2.University; ```
Besides [Luke Ford's answer](https://stackoverflow.com/a/29103554/6884) *(which is correct)*, there's another gotcha to consider: MS Access *(at least Access 2000, where I just tested it)* seems to match the columns by name. In other words, when you execute the query from Luke's answer: ``` INSERT INTO MainTable SE...
How to define destination for an append query Microsoft Access
[ "", "sql", "database", "ms-access", "inner-join", "" ]
I have a transaction table with the following structure: ``` select t.[GUID], t.[ID], ts.Description "Status", t.Payee, t.Amount, t.SequenceNumber from [Transaction] t inner join TransactionStatus ts on t.StatusID = ts.ID GUID | ID | Status | Payee | Amount | SequenceNumber AF732CF...
If it's SQL-Server you can use a [CTE](https://technet.microsoft.com/en-us/library/ms190766%28v=sql.105%29.aspx) + [`ROW_NUMBER`](https://msdn.microsoft.com/en-us/library/ms186734.aspx): ``` WITH CTE AS ( select t.[GUID], t.[ID], ts.Description "Status", t.Payee, t.Amount, t.SequenceNumber, rn = row_num...
You can calculate the `MAX(ID)` and it's related `[GUID]` in a subquery and `JOIN` to it in order to get the desired results: **Sample subquery:** ``` SELECT [GUID] , MAX(ID) MaxId FROM Transaction GROUP BY [GUID] ``` Would produce: ``` GUID MaxId 1F7D880C-E7C0-E411-B8...
Selecting records with maximum value in group
[ "", "sql", "sql-server", "sql-server-2012", "" ]
I'm using SQL Server 2008 and have a database that includes the day of week in a bit type such as: ``` JobID int JobDescription nvarchar(50) M bit Tu bit W bit Th bit F bit Sa bit Su bit ``` I need to import data ...
First import file as is into temp table and then insert into destination table from: ``` DECLARE @t TABLE(JobID INT, JobDescription NVARCHAR(MAX), DayOfTheWeek NVARCHAR(MAX)) INSERT INTO @t VALUES (100, 'Backup', 'Monday'), (101, 'Reports', 'Monday'), (102, 'Cleaning', 'Tuesday') SELECT JobID, JobDescript...
I have a two-step solution to your problem. First, you can generate 7 columns representing the bits for each day of the week using Excel. The following screen captures show how you can do this: ![enter image description here](https://i.stack.imgur.com/F5RWp.png) ![enter image description here](https://i.stack.imgur.c...
Import DayOfWeek Name as Bit in SQL
[ "", "sql", "sql-server", "" ]
I am trying to understand why the SQL command of `MAX(SUM(col))` gives the a syntax error. I have the two tables as below-: ``` +--------+--------+---------+-------+ | pname | rollno | address | score | +--------+--------+---------+-------+ | A | 1 | CCU | 1234 | | B | 2 | CCU | 2134 | |...
The error is `1111: invalid use of group function`. As for why specifically MySQL has this problem I can really only say it is part of the underlying engine itself. `SELECT MAX(2)` does work (in spite of a lack of a `GROUP BY`) but `SELECT MAX(SUM(2))` does not work. This error will occur when grouping/aggregating fun...
Aggregate functions require an argument that provides a value for each row in the group. Other aggregate functions don't do that. It's not very sensical anyway. Suppose MySQL accepted `MAX(SUM(col))` -- what would it mean? Well, the `SUM(col)` yields the sum of all non-`NULL` values of column `col` over all rows in th...
sql - Why doesn't MAX() of SUM() work?
[ "", "mysql", "sql", "sum", "max", "" ]
I've following table: ``` PERSON_ID EFFECTIVE_END_DATE ASSIGNMENT_ID FULL_NAME 33151 2013-08-04 00:00:00.0 33885 Test, C 33151 2013-10-04 00:00:00.0 33885 Test, C 33151 2015-02-19 00:00:00.0 33885 Test, C 33151 2013-08-04 00:00:00.0 33885 ...
In Oracle you can use: ``` select * from (SELECT your_column_name FROM table_name order by EFFECTIVE_END_DATE desc) where rownum=1; ``` OR ``` SELECT * FROM ( SELECT your_columns, row_number() over (order by EFFECTIVE_END_DATE desc) EED FROM table_name) WHERE EED = 1 ``` OR ``` SELECT * FR...
You might have duplicate rows too. You could use Analytic ranking function to fetch the required rows. **Set up:** ``` SQL> CREATE TABLE Table1 2 (PERSON_ID int, EFFECTIVE_END_DATE varchar2(21), ASSIGNMENT_ID int, FULL_NAME varchar2(7)); Table created. SQL> SQL> INSERT ALL 2 INTO Table1 (PERSON_ID, EF...
How to select max date using SQL without using group by clause . There are solutions for this which have group by clause I want solution without it
[ "", "sql", "oracle", "date", "group-by", "" ]
Consider the following table schema: ``` ---------------------------------- | ID | MinValue | MaxValue | ---------------------------------- | 1 | 0 | 10 | | 2 | 11 | 20 | | 3 | 21 | 30 | ``` I want to be able to pass an integer, and have it return the ap...
try this ``` SELECT ID FROM MyTable WHERE @input BETWEEN MinValue AND MaxValue ``` **DESCRIPTION of BEETWEEN** The SQL `BETWEEN` Condition is used to retrieve values within a range in a `SELECT`, `INSERT`, `UPDATE`, or `DELETE` statement. **SYNTAX** The syntax for the SQL `BETWEEN` Condition is: expression `BETWE...
Try this, ``` SELECT ID FROM MyTable WHERE @input BETWEEN MinValue AND MaxValue. ``` Or flip the equality signs in your statement. ``` SELECT ID FROM MyTable WHERE MinValue <= @input AND MaxValue >= @input ```
Check if Integer is between a range of column values
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have 2 tables, **indexInfo**: ``` [indexId] [name] [type] 101 nameA Cars 102 nameB Trucks 103 nameC Cars ``` **userGroupXindexInfo** ``` [usergroupnumber] [indexId] 201 101 201 103 202 102 202 103 203 103 ``` ...
One way to do this is to use a `in` predicate to limit the `indexId` to those matching the specified groups: ``` select indexId from indexInfo where type = 'Cars' and indexId in ( select indexId from userGroupXindexInfo where usergroupnumber in (201,202,203) ) ```
You can use `EXISTS` for that: ``` SELECT t.IndexId FROM indexInfo t WHERE t.Type='Cars' AND EXISTS ( SELECT * FROM userGroupXindexInfo i WHERE t.IndexId = i.IndexId ) ``` The first condition `t.Type='Cars'` verifies the type. The second condition `EXISTS (...)` verifies that the index is assig...
How to construct sql query for the following case?
[ "", "sql", "" ]
Data is like so, (table1 links up to table2) on table1.col2 = table2.col2 Based on that criteria, Employee 5 below assigned to Area 1 in first table, however in second table that employee is not assigned to Area 1, so the result that would return would only be the first record of the first table (emp5, a1) Example b...
This is tricky. You need employees who are in both tables. Then you need to check that col2 is different on one of the rows. The following does this comparison using `union all`: ``` select col1, col2, max(which) from ((select col1, col2, 1 as which from table1 t1 where exists (select 1 from table2 t2 ...
You can use MINUS, it is more intuitive. The syntax can be different in SQL Server, MySQL or Oracle, like you can see <http://blog.sqlauthority.com/2008/08/07/sql-server-except-clause-in-sql-server-is-similar-to-minus-clause-in-oracle/> But I like MINUS, for instance ``` select t1.Col1, t1.Col2 from table1 t1 ...
Differences between two tables
[ "", "sql", "" ]
It's hard to explain with words what I'm trying to accomplish so here's an example. Let's say we have the following table: ``` Customer Group BeginDate ParentCustomer 1469046 3939 7/1/2010 1311044 1469046 3939 8/1/2010 1311044 1469046 4144 1/1/2011 1460224 1469046 4147 2/1/2...
``` select * from ( SELECT *, LAG(Group, 1,0) OVER (ORDER BY BeginDate) AS PreviousGroup FROM table ) where PreviousGroup is null or PreviousGroup <> group ```
If you are using SQL Servier 2005 or SQL Server 2008 then you can use this. ``` SELECT T.* FROM T OUTER APPLY ( SELECT TOP 1 T2.[Group] FROM T AS T2 WHERE T2.Customer = T.Customer AND T2.BeginDate < T.BeginDate ORDER BY T2.BeginDate DE...
Return the first iteration of the set of values even if they repeat,
[ "", "sql", "sql-server", "database", "t-sql", "" ]
I want to create a query for the cheapest package for a holiday to Spain, given package ID. I'm just stuck to how to go about it when executing my query. I need help on what to include in the values for the 'package' table and I also need help on how to present the query. Here is the table: ``` USE [zachtravelage...
First, for your insert statement for 'package', you don't specify packageId since it's an identity column. Instead it should look something like this ``` Insert Into package (hotelID, excursionID, transportID, flightID) Values (1, 54, 43, 23) ``` Then to run a SELECT Query to find the cheapest package to Spain you wi...
Apparently you need to create a total of five tables. Because of the foreign keys you'll have to insert data in the packages table last. Let's assume all that is completed and you now want to query. If you're given the packageID then you already have the answer. I'm not sure what you mean by that. If you want the mini...
SQL help on query
[ "", "sql", "sql-server", "insert", "" ]
I have the below table (sorry couldn't figure out how to post a table... in bold are the field names) **code desc channel date** 1001 A supermarket 10-oct 1001 B minimarket 15-dic 1003 A restaurant 07-may 1003 B bar 30-abr 1003 A restaurant 12-dic 1002 B kiosk 10-oct I am trying to get the latest record for eac...
You can get the results using a query: ``` select t.* from table as t where t.date = (select max(t2.date) from table as t2 where t2.code = t.code); ``` I'm not sure what your other table looks like, but you could fix this into a query like: ``` update secondtable set val = (select channel from tab...
Another answer (as the others posted work also) is to use a temporary table. It does require 3 SQL statements, but might be faster than the nested queries below: (assuming the two tables you have are called t1 and t2, and I use MySQL) ``` CREATE TEMPORARY TABLE t3 AS SELECT code, descr, channel, MAX(date) as mxdate ...
Update another table based on latest record
[ "", "sql", "ms-access", "" ]
Suppose I have an sql query like the following (I realize this query could be written better, just bear with me): ``` SELECT aT.NAME FROM anothertable aT, ( SELECT ts.slot_id, tgm.trans_id, tagm.agent_id FROM slots ts, transactions tgm, ...
Just use a subquery: ``` SELECT at.Name FROM anotherTable aT JOIN (select 230743 as SLOT_ID, 3270893 as TRANS_ID, 2307203 as AGENT_ID from dual select 078490, 230897, 237021 from dual ) i on i.trans_id = at.trans_id AND i.agent_id = aT.trans_id; ```
The subquery method worked. Since this is Oracle, the syntax turned out to be: ``` SELECT aT.Name FROM anotherTable aT, (select 1907945 as SLOT_ID, 2732985 as TRANS_ID, 40157 as AGENT_ID FROM DUAL union select 1907945, 2732985, 40187 FROM DUAL ) inner WHERE inner.trans_id = aT.trans_id AND INNER.agent_id = aT.tr...
sql inner table substitution
[ "", "sql", "oracle11g", "subquery", "" ]
I have a `sas` data set consisting of more than 100 variables. Variables `pid` - a character variable and `year` - a numeric variable identify observations in the data set. How can I create a new data set consisting of observations that have unique `pid` and `year` combination. That is, if a given `pid` and `year` com...
I don't use much of data step. I use proc sql and is easy for me. ``` proc sql; create table new_dataset as select * from old_dataset as a join (select pid, year, count(1) from old_dataset group by pid, year having count(1)<2) as b on a.pid=b.pid and a.year=b.year; run; ``` inner query only gets...
Simple use of `first.` and `last.` in a data step will do this. Run `proc sort` if the data is not already sorted by pid and year. ``` proc sort data=have; by pid year; run; data want; set have; by pid year; if first.year and last.year then output; /* only keep unique rows */ run; ```
How to create SAS data set extracting observations with unique keys
[ "", "sql", "sas", "" ]
I tried some queries and its taking me to almost my result using JOINs. But Please suggest if any better way to do this ? I have table like this : ``` Name Number A 1 B 2 C 3 D 4 E 5 ``` I want the result to be like : ``` Name Number Name number A 1 B 2 C ...
Below Query will help you ``` SELECT a.NAME,a.Number,b.NAME,b.Number FROM (SELECT ROW_NUMBER() OVER(ORDER BY Number) AS ROW,NAME,Number FROM #temp WHERE Number %2 <>0) a LEFT OUTER JOIN (SELECT ROW_NUMBER() OVER(ORDER BY Number) AS ROW,NAME,Number FROM #temp WHERE Number %2 =0) b ON a.ROW = b.ROW ```
Using full join as there could be %2 = 1 less than %2 = 0 ``` DECLARE @a AS TABLE (a VARCHAR(10), b INT) INSERT INTO @a VALUES ('A',1),('B',2),('C',3),('D',4),('E',5); SELECT a.a,a.b, b.a, b.b FROM ( SELECT a.a, a.b, DENSE_RANK() OVER(ORDER BY a.b) AS rownum FROM @a a WHERE a.b%2 = 1 ) a FULL JOIN ( SELECT a.a, a.b,...
SQL Query for the Pattern
[ "", "sql", "sql-server", "" ]
I created the following query ``` select c.id as eid, c.created, e.class_id, min(e.event_time), min(cn.create_time) as lead_date from bm_emails.cid378 c left join bm_sets.event378 e on e.eid = c.id left join bm_sets.conversion378 cn on cn.eid = c.id where e.class_id = 36 group by eid, created, ...
You can use the result of your Min in your condition, however, you will need to use `HAVING`, not `WHERE`. Reference: <http://www.mysqltutorial.org/mysql-having.aspx>
The WHERE clause must be executed first, because in your query, MIN runs on the results of the query. You'll need a join or a subquery to do what you want.
What happens first: min() in selector or where in condition?
[ "", "mysql", "sql", "" ]
I have a table with columns `Date` and `Amount`: ``` CustID Date Amount 1 20150301 10000 1 20150302 5000 1 20150303 15000 2 20150208 9000 2 20150201 5000 2 20150202 6000 ``` I want to set `Amount` to zero when `Date` is after a certain date. ...
I would do this using window functions: ``` with toupdate as ( select t.*, min(date) over (partition by CustId) as mindate from table t ) update toupdate set amount = 0 where date > mindate; ```
You can use the following query that checks if `date` is not equal to `MIN(Date)`: ``` UPDATE Mytable SET Amount = 0 FROM Mytable AS t WHERE [date] <> (SELECT MIN([Date]) FROM Mytable WHERE CustId = t.CustID) ``` or, alternatively, use a `CTE`: ``` ;WITH MIN_CTE AS ( SELECT MIN(...
Set a table field to zero based on a date in another field
[ "", "sql", "sql-server", "t-sql", "sql-server-2008-r2", "" ]
Is it possible to grab the last n inserts in a relational table without using a Date field ? For example in the table `Author`: ``` Author(authid, f_name, l_name) ``` Also, authid is not a natural number (eg. 1,2,3,4..) but a string (example: JohnM32015) I am using MySQL.
A *table* doesn't have a guaranteed sort order. A *query* does, if it explicitly defines one. If, for example, your records have an incrementing `authid` value then the last N inserts would be the highest N values for that column. So you'd order by that column descending and take the top N: ``` SELECT * FROM Author OR...
If the `authid` is auto-increment then you can do ``` select * from author order by authid desc ``` To get only a limited number of records use `top n` in SQL-Server or `limit n` in MySQL for instance.
Select n last linesChubb from table
[ "", "mysql", "sql", "" ]
I want to perform self join on the following query: ``` select RANK() OVER (PARTITION BY CARD_ID, BE_BUSINESS_DATE ORDER BY CARD_TXN_SEQ_NUMBER) as Trip_Leg_Id from [dbo].[Src_Nol_Txns] s1 inner join ``` so that, I join the current record with the record of rank -1 how to achieve that?
``` with cte as ( SELECT * , LAG(CARD_TXN_SEQ_NUMBER, 1,0) OVER (PARTITION BY CARD_ID, BE_BUSINESS_DATE ORDER BY CARD_TXN_SEQ_NUMBER) AS PreviousSEQ FROM table ); select cte1.*, cte2.* from cte as cte1 join cte as cte2 on cte2.CARD_ID = cte1.CARD_ID and cte2.BE_BUSINESS_DATE = cte1.B...
Here's a way to do it ``` With TripID AS ( select RANK() OVER (PARTITION BY CARD_ID, BE_BUSINESS_DATE ORDER BY CARD_TXN_SEQ_NUMBER) as Trip_Leg_Id from [dbo].[Src_Nol_Txns] s1 ) select * from TripID a join TripID b on b.Trip_Leg_Id=a.Trip_Leg_Id - 1 and a.CARD_ID=b.CARD_ID and a.BE_BUSINESS_DATE =b.BE_BUSINES...
Self join in rank query
[ "", "sql", "sql-server", "t-sql", "sql-server-2012", "self-join", "" ]
I want to get top 10 posts based on score, and get 10 comments for each post. I am using the following query: ``` with a as ( SELECt TOP 10 Score,Post.ID as PostID FROM Post order by Score desc ), b as (select PostID,ID as CommentID from PostComment) select * from a left join b on b.PostID = a.PostID `...
Try this: ``` WITH a AS ( SELECT TOP 10 Score , Post.ID AS PostID FROM Post ORDER BY Score DESC ) SELECT * FROM a OUTER APPLY ( SELECT TOP 10 pc.PostID , pc.ID AS CommentID FROM PostComment pc WHERE pc.PostID = a.PostID --ORDER BY SomeColumn ) ...
Something along these lines would work. ``` with a as ( SELECt TOP 10 Score , Post.ID as PostID FROM Post order by Score desc ), b as ( select PostID , ID as CommentID , ROW_NUMBER() over (partition by PostID order by ID) as RowNum from PostComment ) select * from a left join b ...
get top 10 posts and 10 comments for each post sql
[ "", "sql", "sql-server", "t-sql", "sql-server-2012", "" ]
I have a trigger in SQL Server that needs to check on an update the number of rows with a value between a certain amount and do something accordingly. My current code is something like this: ``` IF EXISTS(SELECT COUNT(id) as NumberOfRows FROM database WHERE id = 3 AND value <= 20 and value > 2 ...
The reason is that the `Exists` function is checking the result of the sub-query for `existing` - are there any rows or not. And, as you return the `COUNT`, it'll never be not-existing - `COUNT` returns `0` if there are no rows presented in database. Try to store the resulting count in a local variable, like in this q...
I would do it like so (single line): ``` IF ((SELECT COUNT(id) FROM table WHERE ....)>18) BEGIN ...do something ``` You can even do between in a single line ``` IF ((SELECT COUNT(id) FROM table WHERE ....)between 2 and 20) BEGIN ...do something END ```
SQL SELECT statement within an IF statement
[ "", "sql", "sql-server", "select", "if-statement", "count", "" ]
``` create table Department ( Dep_ID int not null, Dep_Name varchar(30), primary key (Dep_ID), ) create table Course ( C_ID int not null, C_Name varchar (30) not null, C_Duration varchar (10) not null, DegreeType varchar (20), Dep_ID int, primary key (C_ID), constraint DEP_ID1 foreign key (Dep_ID) references Departmen...
I had done a research and get to know that this problem can be resolve by changing the line : `constraint CO_ID foreign key (C_ID) references Course(C_ID) on update cascade,` to `constraint CO_ID foreign key (C_ID) references Course(C_ID) on update No Action,` I have get a explanation on the following link : [Foreign ...
When you are adding foreign key ``` They need to be exactly the same data type in both tables. ``` Try with your query it works fine with me i just remove "," from end of your column ``` CREATE TABLE Department ( Dep_ID INT NOT NULL, Dep_Name VARCHAR(30), PRIMARY KEY (Dep_ID) ) CREATE TABLE Course ( C_ID INT NOT NU...
can someone explain why im getting this error with sql query
[ "", "mysql", "sql", "sql-server", "sql-server-2008", "" ]
is it possible to convert a number into a day of the week ? i've tried ``` to_date(1,'DAY') to_date('1','DAY') ``` with no luck.
You can do the following to convert the a number into a day of the week. Keep in mind that the result you get will depend on your NLS settings (for example, your week might start on Sunday or it might start on Monday, etc.): ``` SELECT TO_CHAR(NEXT_DAY(sysdate, 1), 'Day') FROM dual; ``` The above will convert the num...
Ironically, this is one place where the old-fashioned `decode()` is useful: ``` select decode(<your number>, 1, 'Mon', 2, 'Tue', . . . , 7, 'Sun') ``` This is interpreting the question as returning the day of the week for the day number of the week. Admittedly, the code does suggest that you actually want a date, but...
convert number into day oracle plsql
[ "", "sql", "oracle", "" ]
I'm trying to write a stored procedure to return the maximum value of a column + 1 but for some reason it doesn't want to work. ``` DECLARE @ID int; SET @ID = SELECT MAX(ID) + 1 FROM tbl; ``` I can't for the life of me see what is wrong. It gives me the error of: > incorrect syntax new the keyword 'SELECT'
Use parentheses `( ... )`: ``` DECLARE @ID int; SET @ID = (SELECT MAX(ID) + 1 FROM tbl); ``` or `SELECT` as [suggested by Giorgi](https://stackoverflow.com/a/29148059/284240). `SET` is the ANSI standard way of assigning values to variables, `SELECT` is not. Apart from that using `SELECT` to assign values to variables...
No need for `SET`. Select value directly: ``` DECLARE @ID int; SELECT @ID = MAX(ID) + 1 FROM tbl; ```
Issues with SQL Max function: "Incorrect syntax new the keyword 'SELECT' "
[ "", "sql", "sql-server", "" ]
``` SELECT CATEGORY FROM PEA_TEMPLATE WHERE TEMP_ID = 000001 AND TEMP_VERSION = 2 ``` This query returns `'000001','000002'` which is saved in `CATEGORY` column as in this format. ``` SELECT * FROM HR_CATEGORY WHERE CAT_CODE IN ('000001', '000002') ``` This select is working fine with row string ``` SELECT * ...
If CATEGORY can have concatenated strings with apostrophe e.g. `'000001'` or `'000001','000002'`, then better to use LIKE with JOIN construction, like this: ``` SELECT * FROM HR_CATEGORY INNER JOIN (SELECT CATEGORY FROM PEA_TEMPLATE WHERE TEMP_ID = 000001 AND TEMP_VERSION = 2) PEA ON PEA.CATEGORY LIKE '%'''+CAT_...
Your subquery is only returning a single row with the content: > "'000001','000002'" For the IN clause to work each value must be separate as two rows: > '000001' > > '000002' You must split the value from the CATEGORY column into multiple strings. To do that you could use a string-splitting-function. There are man...
How to use IN in SQL Server with Select
[ "", "sql", "sql-server", "t-sql", "" ]
I have written a query to check the completeness of my table with a universal table. The query is a s follows ``` SELECT * FROM Universal WHERE UNIVERSAL.TYPE=MYTYPE AND Universal.CLASS=MYCLASS AND Universal.ID NOT IN (SELECT Mytable.ID FROM Mytable) ``` As you see I filter the universal table before looking for ...
``` SELECT * FROM Universal WHERE UNIVERSAL.TYPE=MYTYPE AND Universal.CLASS=MYCLASS AND Universal.ID NOT IN (SELECT Mytable.ID FROM Mytable WHERE Mytable.ID IS NOT NULL) ``` Nulls and not in...! The `SELECT` returns rows where the `WHERE` clause is `TRUE`, and doesn't return `FALSE` row...
So you want to SELECT everything from Universal that is not in Mytable? Using a LEFT JOIN will select everything from and Univeral and only rows from Mytable that match up to something in Universal. So if Mytable.ID is null then that row of Universal does not have a matching row in Mytable: ``` SELECT * FROM Universal...
Writing a SQL query in a different way
[ "", "mysql", "sql", "oracle", "" ]
I can't find problem. I have many tables joined each other. I need to get count of form instances from `FormInstances` table (should count `Id` column), but It returing wrong data. So my query looks like: ``` DECLARE @dateStart DATE = NULL, @dateEnd DATE = NULL, @workshop NVARCHAR(60) ...
You are doing a join, which is multiplying the number of records. Try using distinct within the count to remove duplicates: ``` COUNT(distinct FI.Id) ```
If you just want to get: ``` Count of Instances 5 ``` You should change: ``` SELECT COUNT(FI.Id) AS [Count of Instances], FI.Id AS [Instance Ids] FROM.... ``` To this: ``` SELECT COUNT(*) AS [Count of Instances] FROM.... ``` But I don't see how the query you posted can return the results yo...
SQL. Wrong result of COUNT() function
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "count", "" ]
I'm trying to wrap my head around these two functions in the [Spark SQL documentation](http://spark.apache.org/docs/1.2.0/api/scala/index.html#org.apache.spark.sql.SchemaRDD)– * *def union(other: RDD[Row]): RDD[Row]* Return the union of this RDD and another one. * *def unionAll(otherPlan: SchemaRDD): SchemaRDD* ...
In Spark 1.6, the above version of `union` was removed, so `unionAll` was all that remained. In Spark 2.0, `unionAll` was renamed to `union`, with `unionAll` kept in for backward compatibility (I guess). In any case, no deduplication is done in either [`union` (Spark 2.0)](https://spark.apache.org/docs/2.0.0/api/pyth...
`unionAll()` was deprecated in [Spark 2.0](https://spark.apache.org/docs/latest/api/python/pyspark.sql.html), and for all future reference, `union()` is the only recommended method. In either case, `union` or `unionAll`, both do not do a SQL style deduplication of data. In order to remove any duplicate rows, just use ...
Why would I want .union over .unionAll in Spark for SchemaRDDs?
[ "", "sql", "scala", "apache-spark", "union", "union-all", "" ]
I need to copy a set of data from TableA into TableB, like so: ``` INSERT INTO TableB(id,field1,field2) SELECT id,field1,field2 FROM TableA ``` The above will work well, however `TableB` might already contain some of the records which I need to copy, identified by the PK `id`. Thus, how can I add a clause to **only...
You can take a look for 3 methods comparing [NOT IN vs. NOT EXISTS vs. LEFT JOIN / IS NULL](http://explainextended.com/2009/09/18/not-in-vs-not-exists-vs-left-join-is-null-mysql/). > The best way to search for missing values in *MySQL* is using a *LEFT* > *JOIN* / *IS NULL* or *NOT IN* rather than *NOT EXISTS*. --- ...
INSERT INTO TableB(id,field1,field2) SELECT T2.id,T2.field1,T2.field2 FROM TableA as T1 inner join TableB as T2 on T1.id <> T2.id
How to transfer data between tables, only where id does not exist
[ "", "mysql", "sql", "database", "database-design", "" ]
Have 2 tables with a column `Country` and I'm trying to get the results one for the same countries in both, one for countries in the first table but not in the second, and one for countries in second table but not in the first. `Tb1.Country`: ``` Botswana Burkina Faso Cameroon Ethiopia Ghana Ghana Ghana Ghana Ghana M...
You could use a UNION query to do this in Access: ``` SELECT TB1.Country, "Country in Table 1, but not Table 2" as result FROM tb1 LEFT JOIN tb2 ON tb1.country = tb2.country WHERE tb2.country IS NULL UNION ALL SELECT TB2.Country, "Country in Table 2, but not Table 1" FROM tb2 ...
There's multiple set operations in Standard SQL, not only UNION, but also EXCEPT and INTERSECT. Get the countries common in both tables: ``` select country from t1 intersect select country from t2 ``` Get the countries only in the first table: ``` select country from t1 except -- Oracle calls this MINUS select coun...
What is the simplest query in SQL to get the differences between 2 tables?
[ "", "sql", "ms-access", "vba", "" ]
I have the following queries looking at join tables: ``` select scholarship_id as scholId, count(scholarship_id) as incompleteCount from applicant_scholarship group by scholarship_id ``` and ``` select scholarship_id as scholId, count(scholarship_id) as completeCount from applicant_comp_schol group by ...
``` select scholarship_id as scholId, count(scholarship_id) as incompleteCount null as completeCount from applicant_scholarship group by scholarship_id group by scholarship_id Union select scholarship_id as scholId, null, count(scholarship_id) from applicant_comp_schol group by scholarship_id ```
You should probably have one more table which contains the full list of records, which would be your base (to make sure you catch the "zeroes"). Assuming you do, you can keep your two queries as subqueries that you left-join against: ``` select s.scholarship_id ,nvl(inc.num_records, 0) incompleteCount ,nvl...
SQL Combining two queries of different tables
[ "", "sql", "oracle", "" ]
I have the following records: ``` ID FIRST LAST CATEGORY 123 Tom Smith Teacher 123 Tom Smith Tutor 345 Julia Brown Banker 345 Julia Brown Tutor 567 Dan Davids Fireman 567 Dan Davids Golfer 567 Dan Davids Painter ``` I want to exclude all records that has 'Tutor' as a value. My...
``` SELECT id, first, last, category FROM names WHERE ID NOT IN (SELECT id FROM names where category = 'Tutor') ```
Use a SELECT with a JOIN and a WHERE clause that excludes the 'Tutor' value. You didn't describe your schema well enough for me to give an exact query, so you may have to change some naming, but this is the idea: ``` SELECT names.id, `first`, `last`, category FROM names JOIN category on names.category_fk = category.i...
Do not return any records if one value exist in a field?
[ "", "sql", "" ]
Running following statement in DB2 CLP (Command Window) > db2 "truncate table MYSCHEMA.TABLEA immediate" ``` DB21034E The command was processed as an SQL statement because it was not a valid Command Line Processor command. During SQL processing it returned: SQL0969N There is no message text corresponding to SQL er...
The version of the DB2 client you're using doesn't seem to match that of the server, this is why you cannot see the actual error message for SQLCODE -20356. If you could, you'd see this: > The table MYSCHEMA.TABLEA cannot be truncated because DELETE triggers > exist for the table, or the table is the parent in a refer...
I had this problem recently too. In my case I had to do a COMMIT WORK right before TRUNCATE. This solved my problem. Please try and tell us if this helped.
How to Truncate table in DB2? Error: Not a valid Command Line Processor command
[ "", "sql", "database", "db2", "truncate", "db2-luw", "" ]
I have a column `rating` with number 0 - 1000 I want to order these rows by `rating ASC` but I want that if the rating is between 0-99 they will have the same sorting order (same for 100-199, 200-299, etc). And these groups I want to have randomized when returned from the DB Is this possible with SQL? Example: This...
Just divide the ratings by 100 and then use `random()`: ``` SELECT * FROM T ORDER BY Rating/100,random() ``` Assuming that `Rating` is an integer, the division automatically truncates the result to also be an integer, thus handily treating `199/100` and `101/100` as both just being `1`.
Probably try using offset Example SELECT rating FROM ratingtable ORDER BY rating ASC LIMIT 100 OFFSET 0; this will display rating between 1-100 to display ratings between 101-200 just set the offset to 100
SQL Order by grouping
[ "", "sql", "postgresql", "group-by", "sql-order-by", "" ]
I would like to ignore if there are any zero values in the first days of production. ``` SELECT D_DATE, PRODUCE FROM PRODUCTION ``` **Dataset** ``` Date Produce 1/1/2015 0 1/2/2015 0 1/3/2015 0 1/4/2015 6 1/5/2015 5 1/6/2015 2 1/7/2015 0 1/8/2015 1 1/9/...
For simplicity I assume that there is at least one day with produce > 0. ``` SELECT d_date, produce FROM production WHERE d_date >= ( SELECT MIN(d_date) FROM production WHERE produce != 0 ) ; ```
You can use SUM as analytical function to calculate the cumulative sum of produce and filter those greater than zero. ``` select d_date, produce from ( select d_date, produce, sum(produce) over (order by d_date) cuml_produce from production ) where cuml_produce > 0 order by d...
How to ignore the first zeros in the result of a query
[ "", "sql", "oracle", "" ]
I have problem that I have to make my code shorter . code: ``` IF @result_var = @expected_value BEGIN INSERT INTO reports.consistencycheckhistory VALUES ( Getdate(), @rule_guid, 'Ok', ...
``` IF @result_var = @expected_value BEGIN SET @Status = 'Ok' END ELSE BEGIN SET @Status = 'Error' END IF CONVERT(DATE,@check_time) <> CONVERT(DATE, Sysdatetime()) BEGIN SET @ok_days_count = @ok_days_count + 1; END ELSE BEGIN SET @ok_days_count = 0; END INSERT INTO reports.consistencycheckhistory VAL...
``` IF @result_var = @expected_value BEGIN SET @Status = 'Ok' END ELSE BEGIN SET @Status = 'Error' END IF @Status = 'Ok' BEGIN IF CONVERT(DATE, @check_time) <> CONVERT(DATE, Sysdatetime()) BEGIN SET @ok_days_count = @ok_days_count + 1; END ELSE BEGIN @ok_days_count=@ok_days_count END end EL...
Making SQL statement efficient and easy to understand
[ "", "sql", "sql-server", "" ]
I have the following data in my webinar\_timing table in mysql database start\_time and end\_time are of type datetime ``` id | webinar_id | start_time | end_time ------------------------------------------------------------------- 1 | 5 | 3/18/2015 6:00:00 PM | 3/18/2015 7:00:00 PM ...
Something like: ``` select webinar_id , count(*) AS total , count(case when end_time<NOW() then 1 end) as completed , (select count(1) from webinar_times y where x.webinar_id = y.webinar_id and y.start_time > NOW()) as remaining , min(case when x.start_time > NOW() then x...
You can make an outer join between two grouped queries, e.g. one that counts the total number of webinars and another that both counts the remaining webinars and obtains the start time of the next one: ``` SELECT * FROM ( SELECT webinar_id, COUNT(*) total FROM webinar_times GROUP BY webinar_id ) tota...
Mysql - sql query to get next class based on date
[ "", "mysql", "sql", "" ]
I have a question very similar to another question but I can't quite figure it out. Here is the link to the original question:[Oracle/SQL - Finding records with one value excluding by similar record](https://stackoverflow.com/questions/5169884/oracle-sql-finding-records-with-one-value-excluding-by-similar-record) So s...
Try this: ``` select person, type from table where type = '1' and person not in (select person from table where type is null) ```
Apart from Mark's `NOT IN` approach, this can also be written as a `NOT EXISTS` condition: ``` select p1.person from person p1 where p1.type = 1 and not exists (select 1 from person p2 where p1.person = p2.person and p2.type is null) order by p1.person; ``` It essentia...
Oracle/SQL - Finding records with one value excluding nulls
[ "", "sql", "oracle", "" ]
I want to get the substring of a string like: filename\_ip\_time.pdf I want to select filename\_ip, that is the string till last occurance of '\_'
Use -1 as the start position with INSTR to start searching from the end of the string: ``` select INSTR('filename_ip_time.pdf', '_', -1) from dual ``` So if you want to select filename\_ip, you should do something like this: ``` SELECT SUBSTR ('filename_ip_time.pdf', 0, (INSTR ('f...
Another way for the sake of argument using REGEXP\_REPLACE(): ``` SQL> select regexp_replace('filename_ip_time.pdf', '^(.*)_.*$', '\1') from dual; REGEXP_REPL ----------- filename_ip SQL> ``` Where the regular expression can be read as: Return the first remembered group (\1) where the pattern matches: ``` ^ Start...
Find substring till last occurrence
[ "", "sql", "oracle", "plsql", "" ]
I'm trying to write a query which will pair up impressions and conversions from the same IP address in my database. I have a table of impressions and their IP addresses, and an impression can be of the type 'view' or 'conversion' (defined in the column 'name'). So basically, I need to identify groups of records with t...
You need to use the `HAVING` clause with a conditional count. You also need to remove `name` from the `GROUP BY` as this will treat your two different types separately. ``` SELECT ip_address, COUNT(CASE WHEN Name = 'View' THEN 1 END) AS Views, COUNT(CASE WHEN Name = 'Conversion' THEN 1 END) AS Conver...
You can try this: ``` SELECT i.ip_address AS ip, GROUP_CONCAT(DISTINCT CAST(i.name AS CHAR)) AS nameList, SUM(IF(i.name = 'View', 1, 0)) AS viewCount, SUM(IF(i.name = 'Conversion', 1, 0)) AS conversionCount FROM Impressions i GROUP BY i.ip_address; ``` You will get a comma delimited list of names containin...
SQL query to identify pairs with duplicates
[ "", "mysql", "sql", "" ]
I need to copy information (boolean) from "details" table to "user" table as with "oppossite" value: tables structure: "user" table: ``` id name appear 1 John null 2 Matt null 3 jack null 4 sara null 5 sarah null ``` "details" table: ``` id user_id ...
You need to update with `join and case-when` ``` update user u join details d on d.user_id = u.id set u.appear = case when d.appaer = 'true' then 'false' else 'true' end ; ```
update appear from user table when `true` then `false` and join that two tables with `user_id` ``` update user set appear=(select case when details.appear='true' then 'false' when details.appear='false' then 'true' end from details join user on details.user_id=users.id) ```
MySQL: copy information from table to another with opposite value
[ "", "mysql", "sql", "" ]
So I have a Visitor table, and a Visitor\_activity table. Say: Visitor ``` Visitor_ID Int Visitor_name varchar(20) ``` Visitor\_Activity ``` ID Int Visitor_ID Int Activity_Type char(3) -- values IN or OUT Activity_Time datetime ``` Visitors might sign in and out multiple times in a day. I'd like a nice query to t...
``` SELECT v.* FROM Visitors v JOIN Visitor_Activity va ON va.Visitor_ID = v.Visitor_ID WHERE va.Activity_Type = 'IN' AND NOT EXISTS ( SELECT * FROM Visitor_Activity va_out WHERE va_out....
One way to solve this is to use a correlated not exists predicate: ``` select Activity_Time, Visitor_ID from Visitor_Activity t1 where Activity_Type = 'IN' and not exists ( select 1 from Visitor_Activity where Activity_Type = 'OUT' and Visitor_ID = t1.Visitor_ID and Activity_Time > t1.Activity_T...
SQL Last activity of given type
[ "", "sql", "sql-server", "join", "" ]
![enter image description here](https://i.stack.imgur.com/8K52t.gif) How can I compare the value of amount given in two columns as shown in the attached picture? 'T', 'M' and 'B' in column 1 represent trillion, million and billion respectively. I have tried below mentioned code so far but that's not what I need. ``` ...
You can use string manipulation to extract the numeric portion of the string and the use `CASE` statements to multiply the values to produce a numeric value that can be used to compare the results. **Sample query to perform conversion:** ``` CREATE TABLE #temp (col1 VARCHAR(20), col2 DECIMAL (18, 2)) INSERT INTO #te...
This will demonstrate my comment above. It uses a combination of `LEFT(), RIGHT(), CHARINDEX() and SUBSTRING()` as well as a `CASE` to determine the multiplier value. ``` declare @Text varchar(20) = '$30M Sales in Jan 2014' SELECT @Text [OriginalText] --select only the letter ,Right(left(@Text, CHARINDEX(' '...
Extract a numeric value from a varchar column to compare with a numeric column
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I am trying to write a query where I am filtering by date and also by age , the query would be something like ``` select * from table1 where birthdate >= 'date1' and dead <= 'date2' where age >17 and <55; ``` The table columns is like this > ID---name---lastname---birthdate---deadDate
Your query is really close. However, any time you want multiple conditions in a WHERE clause, you just have to use AND (or OR) in between each. Try this: ``` SELECT * FROM myTable WHERE birthdate >= 'date1' AND death <= 'date2' AND age > 17 AND age < 55; ```
``` select * from table1 where birthdate >= 'date1' and deadDate <= 'date2' and DATEDIFF(birthdate,deadDate) between > 17 and < 55; ```
Select query filtering by datediff
[ "", "mysql", "sql", "subquery", "where-clause", "" ]
![enter image description here](https://i.stack.imgur.com/xNcl3.png) I want to select all values from *Users* and min of `dateUsed` in Code table. How can I do that? I've tried this: ``` SELECT u.firstName, u.lastName, u.fbId, q.dateUsed, u.codesLeft FROM Users u inner join Code q on u.Id = q.userId ``` Bu...
> Adding distinct has no effect As a rule of thumb, `DISTINCT` helps for a single-column `SELECT`s. With multiple columns you need to go for "big guns" - the `GROUP BY` clause. In order for that to work you need to make sure that each item that you select is either a `GROUP BY` column, or has a suitable aggregation f...
Scalar Sub Query ``` SELECT u.firstName, u.lastName, u.fbId, (SELECT TOP 1 dateUsed FROM Code as q WHERE u.Id = q.userId ORDER BY dateUsed ASC), u.codesLeft FROM Users u ``` OR CTE ``` ;WITH SEQ as ( SELECT userId, MIN(DateUsed) as FirstDate, MAX(DateUsed) as lastDate FROM Code GROUP BY userID) SELECT... u....
Select all values from first table and ONLY first value from second table
[ "", "sql", "sql-server", "t-sql", "" ]
I'm not sure it's possible but I would like to select the distinct value of two tables columns. Consider table1 like: ``` ╔══════╗ ║ col1 ║ ╠══════╣ ║ AAA ║ ║ AAA ║ ║ BBB ║ ║ BBB ║ ╚══════╝ ``` and table2 like: ``` ╔══════╗ ║ col1 ║ ╠══════╣ ║ AAA ║ ║ BBB ║ ║ CCC ║ ║ CCC ║ ╚══════╝ ``` The output I would l...
A simple `UNION` would do the tricks ``` SELECT col1 FROM table1 UNION SELECT col1 FROM table2; ``` There is no need to use the `DISTINCT` keyword as `UNION` already handle duplicates. FYI if you use `UNION ALL` the duplicates won't be handled anymore, then you would need to use `DISTINCT`.
Just `union` will do the job, as it will filter out the duplicate records. ``` SELECT col1 FROM table1 UNION SELECT col1 FROM table2 ```
How can I select the distinct value of two tables?
[ "", "mysql", "sql", "distinct", "" ]
This is very weird, so I could use a pair of spare eyes to understand what's happening. So I have this query: ``` WITH x as ( SELECT num_aula, tipo_aula, min(abs(capienza-1)) score FROM aula JOIN ( select num_aula, tipo_aula from aula ...
I think the query you really want is ``` WITH x as ( SELECT num_aula, tipo_aula, min(abs(capienza-1)) score, row_number() over(partition by num_aula, tipo_aula order by score asc ) as seq FROM aula JOIN ( select num_aula, tipo_aula from aula where tipo_au...
The rownum is assigned to the row before any sorting takes place, so I suspect that removing your order by and running without the where rownum = 1 will return: ``` NUM TIPO_AULA SCORE --- -------------------- ---------- 2 Laboratorio 35 1 Laboratorio 35 ``` There...
Why does using "where rownum = 1" not select the first ordered row?
[ "", "sql", "oracle", "" ]
I am trying to do SUM() in a multi-currency setup. The following will demonstrate the problem that I am facing:- ``` Customer ------------------------- Id | Name 1 | Mr. A 2 | Mr. B 3 | Mr. C 4 | Mr. D ------------------------- Item ------------------------- Id | Name | Cost | Currency 1 | Item 1 | 5 | USD ...
Ok, I managed to solve the problem this way:- ``` SELECT innerQuery.Name AS Name, (CASE WHEN innerQuery.Currencies=1 THEN (innerQuery.Amount || innerQuery.Currency) ELSE 'Mutliple-Currencies' END) AS Amount, FROM (SELECT Customer.Name, SUM(Item.Amount), COUNT(DISTINCT Item.Currency) AS Currencies, Item.Currency AS C...
I would suggest two output columns, one for the currency and one for the amount: ``` SELECT c.Name, (case when max(currency) = min(currency) then sum(amount) end) as amount, (case when max(currency) = min(currency) then max(currency) else 'Multiple Currencies' end) as currenc...
SUM in multi-currency
[ "", "sql", "sqlite", "" ]
I need to copy "user1\_id" & "user2\_id" from "battle" table to new table called "user\_battle", tables structure: "battle" table (structure): ``` id user1_id user2_id 1 1 2 2 1 3 3 2 3 4 2 4 5 1 4 ``` "user\_battle" t...
I think you can use `union all` to get the data you want: ``` select id, user1_id from battle union all select id, user2_id from battle; ``` You can put `insert into user_battle(battle_id, user_id)` before this statement for the `insert`.
`insert into` allows you to use a `select` to effectively "copy" data from one table to another. By using `union` you can get separate rows for `user1_id` and `user2_id`. ``` insert into user_battle (battle_id, user_id) ( select id, user1_id from battle union select id, user2_id from battle ) ```
MySQL: copy data from table to another
[ "", "mysql", "sql", "" ]