Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Give an array like this: ``` my_array = [2,3,5,23,4] ``` and a table like this: ``` column1 | column2 ---------+---------- 1 | 2 | 3 | 4 | 5 | ``` How can I insert the array values into a table. Roughly I want to do something like this with SQL: ``` for item...
You need to somehow generate an array "index" for each row in the table. *If* the `column1` value **always** matches the array index, you can do it like this. ``` update test set column2 = (array[2,3,5,23,4])[column1]; ``` However if the value in `column1` does not reflect the array index, you need to generate t...
In Postgres 9.4 use the `WITH ORDINALITY` for this. Faster and cleaner than anything else. ``` UPDATE test t SET column2 = a.column2 FROM unnest('{2,3,5,23,4}'::int[]) WITH ORDINALITY a(column2, column1) WHERE t.column1 = a.column1; ``` * [PostgreSQL unnest() with element number](https://stackoverflow.com/quest...
How to insert array items into PostgreSQL table
[ "", "sql", "arrays", "postgresql", "" ]
I'm struggling to understand the use of `GROUP BY` in this query and am looking for clarification: ``` Flights(flno: integer, from: string, to: string, distance: integer, departs: time, arrives: time, price: real) Aircraft(aid: integer, aname: string, cruisingrange: integer) Certified(eid: integer, aid: integer) Emplo...
The GROUP BY is required to preform aggregation (in this case, taking the average) properly. If you don't group by anything, MySQL will preform this aggregation over your entire table. In other words, if you used your last query it will return the average salary for all aircraft with a cruising range over 1000, with n...
Anytime you select aggregate functions like AVG, SUM, MAX, MIN, etc... alongside other columns, you must group by all columns which are not aggregate functions or constants. The only exception to this I can think of is when you use windowing functions (not available in MySQL). In this example, I'm unclear as to why th...
Basic usage of GROUP BY in SQL
[ "", "mysql", "sql", "group-by", "" ]
Is it possible for me to join the two tables below? My aim is to create a query in `ASP.NET` to list all the messages in *Messages* and *Messages2* in one set of data. **Messages1:** ``` Messages1_ID, Thread_ID, DateCreated, Title, Body ``` **Messages2**: ``` Thread_ID, Messages2_ID, DateSent, DateMsg2Downl...
What you are looking for is a union. This will combine the result of two query. ``` SELECT Messages1.body from Messages1 where Messages1.Thread_ID = '9' union SELECT Messages2.Body from Messages2 where Messages2.Thread_ID = '9' ```
``` SELECT Messages1.body, Messages2.Body from Messages1 inner join Messages2 ON Messages1.Thread_ID = Messages2.Thread_ID where Messages1.Thread_ID = '9' ```
SQL Join on two tables for messages
[ "", "sql", "sql-server", "vb.net", "join", "" ]
I need to calculate the difference between two dates in Oracle sql and show it in the following format: 'x years y months z days'. Now I see two ways to achieve this: The first way is to get the difference in days, and after that, bring it to 'x year y month z days' The second way is to extract years, month, and day...
As another option you could use [the `months_between()` function](https://docs.oracle.com/cd/E11882_01/server.112/e41084/functions102.htm), and manipulate the value that gives you into the three parts. For example, with some sample dates: ``` select months_between(date '2015-03-19', date '2012-01-06') as month_diff fr...
I just used this formula and I add some case where a gap of 1 day between 2 dates will result of 2 days diff. * Case 1 : 08/04/2019 to 30/04/2021 -> 2 years and 22 days * Case 2 : 08/04/2019 to 01/05/2021 (one day more) -> 2 years and 24 days (2 days more) I have corrected the formula : ``` with t (start_date, en...
How to get difference between two dates in Oracle and show it as ' x years y month z days'
[ "", "sql", "oracle", "date", "" ]
Consider following table:- ``` ----------------------------------------- ID TEACHER SUBJECT GRADE ----------------------------------------- 1 Jack Physics 8 2 Paul Chemistry 10 3 Susan English 6 4 Jack Maths 8 5 Jack ...
``` SELECT * FROM table1 t1 WHERE EXISTS ( SELECT null FROM Table1 t2 WHERE t1."TEACHER" = t2."TEACHER" AND t1."SUBJECT" = t2."SUBJECT" AND t1."ID" <> t2."ID" ) ORDER BY "ID" ``` demo: <http://sqlfiddle.com/#!4/3d2bd4/3>
You can use the below select: ``` SELECT a.* FROM (SELECT COUNT(1) cnt, teacher, subject FROM your_table GROUP BY teacher,subject HAVING COUNT(1) > 1)rec, Your_table a WHERE a.teacher=rec.teacher AND a.subject=rec.subject ```
Finding Rows based on a set of same columns in ORACLE
[ "", "sql", "oracle", "" ]
My code is as below, somehow there is always an error near `@Name` ``` DECLARE @Name nvarchar(MAX) = '(mm.dll, ben and jerry.exe)' DECLARE @sql nvarchar(MAX)= 'SELECT OrderName, customer.version, count(DISTINCT company.CID) as Counts FROM [CompanyData] company INNER JOIN [vendor] mav on company.CID = mav.CID...
Put a single quote in your declaration of `@Name` and just remove the hashes(#) in it: ``` DECLARE @Name nvarchar(MAX)='(''mm.dll'', ''ben and jerry.exe'')' DECLARE @sql nvarchar(MAX)= 'SELECT OrderName, customer.version, count(DISTINCT company.CID) as Counts ...
Please add double quotes in @Name variable like.. ``` DECLARE @Name nvarchar(MAX) = '("mm.dll", "ben and jerry.exe")' ```
Execute a sql string in sql server
[ "", "sql", "sql-server", "t-sql", "" ]
I want to format a datetime column like so: "March 2004." Currently, I tried ``` DECLARE @Date VARCHAR(20) = '2004-03-05 01:00' SELECT CONVERT(VARCHAR(20),CAST(@Date AS DATETIME),13) AS DateFormats ``` but not getting the right result.
Something like: ``` DECLARE @Date VARCHAR(20) = '2004-03-05 01:00' SELECT DATENAME(MONTH, @Date) + ' ' + DATENAME(YEAR, @Date) ``` More on `DATENAME` can be found here <https://msdn.microsoft.com/en-gb/library/ms174395.aspx> Essentially it gets the month part of the date and the year part of the date and concatenate...
You should really apply formatting when you present your data, not in the query, but to answer the question, if you're using SQL Server 2012 or above you can use [FORMAT](https://msdn.microsoft.com/en-GB/library/hh213505.aspx) ``` DECLARE @Date datetime = '2004-03-05 01:00' SELECT FORMAT( @Date, 'MMMM yyyy' ) AS DateF...
Datetime Format in Month and Year
[ "", "sql", "t-sql", "" ]
I have a large amount of card tokens (16 digits) uploaded from xml file to sql-server. The problem is I see them as expression, sample below: ``` 3.3733E+15 3.3737E+15 3.3737E+15 3.3737E+15 3.37391E+15 3.37391E+15 3.37398E+15 3.37453E+15 3.37468E+15 3.37468E+15 3.3747E+15 3.37486E+15 3.37486E+15 3.37567E+15 3.3759E+15...
Try to cast your string to float before converting it : ``` SELECT CONVERT(numeric(16,0), CAST(TOKEN AS FLOAT)) FROM MULTICURRENCY_CHECK ``` * See [this fiddle](http://sqlfiddle.com/#!6/a484f/1). I don't know what's the format of those numbers in your XML source, but with the data you provide, you'll end up with 337...
**For SQL Server 2012+, use [TRY\_CONVERT()](https://learn.microsoft.com/en-us/sql/t-sql/functions/try-convert-transact-sql).** The use of ISNUMERIC() in xlecoustillier's edited answer does not protect against conversion failures. Given the following scenario: ``` CREATE TABLE test(a varchar(100)); insert into test...
Convert exponential to number in sql
[ "", "sql", "sql-server", "" ]
I am trying to write a query that will return 1 row for each 'Applicant' with a column that will display the employerId for the applicant if the number of employerIds is 1, otherwise it would return a string on that column saying "Multiple Applications". Please see below, I am working with MSSQL. Could someone guide me...
You can use a simple grouping and make use of MIN to get the value when there's only one item: ``` SELECT Applicant.FirstName, Applicant.Surname, CASE WHEN COUNT(Employer.ID) = 1 THEN CAST(MIN(Employer.Id) AS varchar(10)) ELSE 'Multiple Applications' END AS Employer FROM Applicant INNER ...
``` select min(FirstName) as FirstName, min(LastName) as LastName, case when count(*) > 1 then 'Multiple Applications' else cast(min(EmployerId) as varchar(11)) end as Employer from Applicant as a inner join Employer as e on e.ApplicantId = a.Id group by a.Id ``` It's certainly possible...
SQL Case with conditional display
[ "", "sql", "sql-server", "t-sql", "" ]
I have this table: club(clubname, membername) ``` photography | Jim photography | Eve photography | Alex woodworking | Jim woodworking | Alex cooking | Alex ``` How do I find the names of people who are in at least the same clubs as Jim? In this example, I want to return Alex. --- I know how to find the names ...
you may do it in multiple ways, one way is to use `where not exists` like below: ``` SELECT DISTINCT C1.membername FROM club C1 WHERE NOT EXISTS ( SELECT C2.membername FROM club C2 LEFT OUTER JOIN club C3 ON C2.clubname=C3.clubname AND C3.membername=C1.membername WHERE C2.membername = 'Jim' AND C3.me...
I was looking for a solution similar to a set difference operator which is basically the link PM 77-1 posted. This is what I got in the end: ``` SELECT membername FROM club WHERE clubname NOT IN ( SELECT C.clubname FROM club C WHERE C.clubname NOT IN ( SELECT clubname FROM club WHE...
SQL: Find the names of the people in at least the same clubs as one specific person
[ "", "sql", "" ]
Given the following schema: ``` CREATE TABLE identifiers ( id TEXT PRIMARY KEY ); CREATE TABLE days ( day DATE PRIMARY KEY ); CREATE TABLE data ( id TEXT REFERENCES identifiers , day DATE REFERENCES days , values NUMERIC[] ); CREATE INDEX ON data (id, day); ``` What is the best way to count all distinct...
Several notes: ## Simple query on table `day` ``` SELECT COUNT(DISTINCT day) FROM days WHERE day BETWEEN '2010-01-01' AND '2011-01-01'; ``` While `day` is defined as PK, `DISTINCT` is just expensive noise. ## Recursive CTE with correlated suquery This is the alternative if there is **no `day` table** with uniq...
I'm not really sure why the index on data(day) is slower, that would seem the simplest option. But if that's too slow, you could try creating a materialised view of your days. Basically just: ``` create materialized view days as select day from data group by day; ``` I don't believe postgres updates materialised vi...
Counting distinct rows using recursive cte over non-distinct index
[ "", "sql", "postgresql", "count", "postgresql-9.3", "unique-index", "" ]
I have a `SELECT` which has result: ``` | NAZEV 1 test 2 test 3 test111 4 test111 5 test111 6 test12 ``` I want to add function `SUM()` [or `count`] to result was: ``` | NAZEV | Pocet 1 test 2 2 test111 3 3 test12 1 ``` My current script: ``` select sb.nazev from ...
In order to use functions like SUM() and COUNT() for a specific field you need to use a GROUP BY on that field. Some samples could be found at `http://www.w3schools.com/sql/sql_func_count.asp` your code should become: ``` select sb.nazev, count(sb.nazev) from Aplikacni_log lg join zadavaci_postup zp on zp.id = lg.i...
In order to use `sum` or `count` *and a column to group on*, you need the `group by` clause: ``` select sb.nazev, count(*) from Aplikacni_log lg ... group by sb.nazev order by sb.nazev asc ``` If you don't need a column (or columns) to group on, you can omit the `group by`. The results will be the total `count` or...
add sum() or count () to query
[ "", "sql", "oracle", "" ]
Hope someone can help. I have been trying a few queries but I do not seem to be getting the desired result. I need to identify the highest ‘’claimed’’ users within my table without discarding the columns from the final report. The user can have more than one record in the table, however the data will be completely di...
As you're using MSSQL you can use the `OVER()` clause like so: ``` SELECT [user], mt.ref_num, mt.[date], COUNT(mt.[user]) OVER(PARTITION BY mt.[user]) FROM myTable mt ``` More about the `OVER` clause can be found here: <https://msdn.microsoft.com/en-us/library/ms189461.aspx> As per your comment you can use the w...
If you want to order by the number of record for each user, then use window functions instead of aggregation: ``` SELECT t.* FROM (SELECT t., count(*) OVER (partition by user) as cnt FROM mytable t ) t ORDER BY cnt DESC, user; ``` Note that I added `user` to the `order by` so users with the same count will...
Highest Record for a set user
[ "", "sql", "sql-server", "t-sql", "" ]
I have a string `"abc"`, and I want to search, in a SQL table, for the values that contain either a, b or c. This is what I have right now: ``` Select * from TABLE where NAME like "abc" ; ``` This didn't work, but I know if I try something like ``` where Name like "a" or Name like "b" or .... ``` it will work. Is...
You can use regular expression for this. Have a look at the following : ``` Select * from TABLE where NAME REGEXP "[abc]"; ```
select \* from ab where name REGEXP '[abc]'
SQL search for string containing characters
[ "", "sql", "" ]
Hey I'm having a bit of trouble coming up with the SQL for the action I would like to perform. I have a table listings which has a start\_price field and an active field. I only want to pull up listings that are active(1). I want to order these listings by the current price. I do not have a current price field in eit...
You'll need a GROUP BY and an aggrate function, in this case MAX(): ``` SELECT l.*, /* columnlist here */ COALESCE(MAX(b.current_price), l.start_price) price FROM listings l LEFT JOIN bids b ON l.id = b.listing_id WHERE l.active = 1 GROUP BY l.listing_id ORDER BY price ``` When there are no bids ...
There are multiple ways that you can do the calculation. I think the key idea for you is that you can use a column alias in the `order by` clause. The following does the calculation using a correlated subquery, then using `coalesce()` if there is no match: ``` select l.*, coalesce( (select max(b.price) ...
MySQL - Trying to sort by two different columns from different tables
[ "", "mysql", "sql", "" ]
With a `SAS` dataset like ``` Ob x year pid grp 1 3.88 2001 1 a 2 2.88 2002 1 a 3 0.13 2004 1 a 4 3.70 2005 1 a 5 1.30 2007 1 a 6 0.95 2001 2 b 7 1.79 2002 2 b 8 1.59 2004 2 b 9 1.29 2005 2 b 10 0.96...
You could stick with `proc expand` to insert the missing years into your data (utilising the `extrapolate` statement). I've set the `from` value to `day` as this is a sequential integer check for days which will work with your data as YEAR is stored as an integer rather than a date. Like the other answers, it requires...
Here is a simple approach using `proc sql`. It joins the data with itself twice; once for the forward and once for the backward lag, then takes the required values where they exist. ``` proc sql; create table want as select a.*, b.x as x_f1, c.x as x_l1 from have as a left join ...
Generating Leads and lags for non-consecutive time periods in SAS
[ "", "sql", "sas", "" ]
I am trying to find the max date across multiple columns (in multiple tables). I have an SQL query that I think is almost workable, but am having a hard time debugging it. The problem is that it never returns anything. Any ideas on what I'm doing incorrectly? I don't get any errors, just an empty row "maxdate." Here's...
First join you join to table 2 using table 1's ID and table 3's ID. I presume you mean table 1's ID and table 2's ID? ``` join table2 as t2 on t1.ID = t3.ID ``` Should be: ``` join table2 as t2 on t1.ID = t2.ID ``` Now that this has been changed; I tried your query and it works fine, are you sure that your joins a...
If it's possible for any of the tables to not have any rows for the given @param, the (inner) joins will filter out all of the other tables. Try unioning the dates and get the max of the unions ``` WITH allDates AS ( SELECT UpdateDate FROM Table1 WHERE ID = @param UNION SELECT UpdateDate FR...
SQL: Calculating the Max date across multiple tables
[ "", "sql", "sql-server", "database", "select", "join", "" ]
I want to remove last character in a row but if the last character is "-" . For example my row looks like this: ``` hello-world today-is-monday- ``` It should be like this: ``` hello-world today-is-monday ``` How can i do that in SQL ?
You can use `trim()` function as ``` mysql> select trim( trailing '-' from 'hello-'); +-----------------------------------+ | trim( trailing '-' from 'hello-') | +-----------------------------------+ | hello | +-----------------------------------+ 1 row in set (0.00 sec) mysql> select trim...
If you mean UPDATE the table then this ``` UPDATE table SET field = SUBSTRING(field, 1, CHAR_LENGTH(field) - 1) WHERE field LIKE '%-' ``` If you mean you want to edit the output but not the data in the table then this ``` SELECT CASE WHEN field LIKE '%-' THEN SUBSTRING(field, 1, CHAR_LENGTH(field) - 1) ELSE fiel...
SQL Remove Last Character if it is "-"
[ "", "mysql", "sql", "" ]
I have the following REGEX: ^[-A-Za-z0-9/.]+$ This currently checks whether the value entered into a textbox matches this. If not, it throws an error. I need to check whether anything has already gone into the database that doesnt match this. I have tired: ``` SELECT * FROM *table* WHERE ([url] NOT LIKE '^[-A-Za-z...
This is what I have used in the end: ``` SELECT *, CASE WHEN [url] NOT LIKE '%[^-A-Za-z0-9/.+$]%' THEN 'Valid' ELSE 'No valid' END [Validate] FROM *table* ORDER BY [Validate] ```
> **Disclaimer:** The original question was about MySQL. The SQL Server answer is below. # MySQL In MySQL, the regex syntax is the following: ``` SELECT * FROM YourTable WHERE (`url` NOT REGEXP '^[-A-Za-z0-9/.]+$') ``` Use the `REGEXP` clause instead of `LIKE`. The latter is for pattern matching using `%` and `_` w...
MSSQL Regular expression
[ "", "sql", "sql-server", "regex", "" ]
I have a small mysql table (MySQL version 5.6.23) : ``` +-----------+-----------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-----------+-----------------+------+-----+---------+----------------+ | id | int(6) unsigned | NO | PRI | NU...
You're using row constructors. MySQL treats them exactly like *rows of a table*. Thus `WHERE (id,dividends) >= (660,0.5)` effectively does the same as: 1. `ORDER BY id,dividends`; 2. Find the point at which `(660,0.5)` would sit within that ordering; 3. Filter for only those records that are equal to or greater than t...
Looking at your where clause everything regarding id evaluates to true first and then everything else is evaluated but must not conflict with first id results. Its also possible that you do not have any id greater than 660 which has a dividend greater than 0.5. ``` (id,dividends) >= (660,CAST(0.5 AS DECIMAL(8,6)))...
MySQL row subquery comparison issue
[ "", "mysql", "sql", "subquery", "" ]
## Employee Table ``` Id Name ------------- 1 Joy 2 Moni 3 Evan 4 farhad ``` ## Absent table ``` Date(y/m/d) Id ----------------- 2015/1/1 1 2015/1/3 1 2015/1/4 1 2015/1/5 1 2015/1/1 2 2015/1/4 2 2015/1/5 2 2015/1/5 3 ``` I have need data from a...
Code(Modifying Modifying Giorgi Nakeuri's solution) ``` DECLARE @sd DATETIME, @ed DATETIME SET @sd = '20150101' SET @ed = '20150106' DECLARE @e TABLE ( ID INT , Name NVARCHAR(MAX) ) INSERT INTO @e SELECT 1, 'Joy' UNION SELECT 2, 'Moni' UNION SELECT 3, 'Evan' UNION SELECT 4, 'Farhad' DECLARE ...
Here is demo. It uses some island solution and then XML query technique for concatenating rows to one string: ``` DECLARE @sd DATE = '20150101' , @ed DATE = '20150105' DECLARE @e TABLE ( ID INT , Name NVARCHAR(MAX) ) DECLARE @a TABLE ( ID INT, d DATETIME ) INSERT INTO @e VALUES ( 1, 'Joy' ), ...
How to select multiple rows in one column with a given condition
[ "", "sql", "sql-server", "" ]
I'm pretty new to SQL and have this problem: I have a filled table with a date column and other not interesting columns. `date | name | name2` `2015-03-20 | peter | pan` `2015-03-20 | john | wick` `2015-03-18 | harry | potter` What im doing right now is counting everything for a date ``` select date, count(*) ...
I think you just need to move your `having` clause to the inner query so that it is paired with the `GROUP BY`: ``` with temp_count (date, counter) as ( select date, count(*) from testtable where date >= current date - 10 days group by date having count(*) < 10 ) select * from temp_count ``` If...
In your temp\_count table, you can filter results with the WHERE clause: ``` with temp_count (date, counter) as ( select date, count(distinct date) from testtable where date >= current date - 10 days group by date ) select * from temp_count where counter < 10 ```
Counting an already counted column in SQL (db2)
[ "", "sql", "count", "db2", "" ]
I'm trying to get the most expensive and cheapest items from two different tables. The output should be one row with the values for MostExpensiveItem, MostExpensivePrice, CheapestItem, CheapestPrice I was able to get the price of the most expensive and cheapest items in the two tables with following query: ``` SELECT...
Try this: ``` SELECT TOP 1 FIRST_VALUE(Price) OVER (ORDER BY Price) AS MinPrice, FIRST_VALUE(Name) OVER (ORDER BY Price) AS MinName, LAST_VALUE(Price) OVER (ORDER BY Price DESC) AS MaxPrice, LAST_VALUE(Name) OVER (ORDER BY Price DESC) AS MaxName FROM ( SELECT ExtrasName AS ...
`TOP 1` with `order by` clause should work for you. Try this ``` SELECT * FROM (SELECT TOP 1 ExtrasPrice,ExtrasName FROM Extras ORDER BY ExtrasPrice Asc), (SELECT TOP 1 ItemPrice,ItemName FROM Items ORDER BY ItemPrice Desc) ``` **Note:** `Comma` can be replaced with `CROSS JOIN`
Get most expensive and cheapest items from two tables
[ "", "sql", "sql-server", "" ]
Please suppose you have a multi-column index in an Oracle table: ``` CREATE INDEX MY_USER.MY_INDEX ON MY_USER.MY_TABLE (YEAR, SEMESTER); ``` The column YEAR is NUMBER(4). The column SEMESTER is NUMBER(1). What is the most efficient way to determine the most recent couple (YEAR, SEMESTER)? I think something like thi...
In case `semester` can be only `1` or `2`, this could be efficient: ``` with t as (select max(year), 1 as semester from MY_TABLE where semester = 1 union all select max(year), 2 as semester from MY_TABLE where semester = 2) select MAX(TO_CHAR(YEAR) || TO_CHAR(SEMESTER)) from t; ``` Of course, th...
Question: What is the most efficient way to determine the more recent couple (YEAR, SEMESTER)? If this is a one off query that will not need to be optimized how about Select MAX(TO\_CHAR(YEAR) || TO\_CHAR(SEMESTER)) FROM MY\_TABLE; Not an elegant solution but it works.
Oracle multi-column index: determine the most recent couple (year, semester)
[ "", "sql", "oracle", "max", "" ]
What is the best way to keep updates (diffs) of the some entity in the database? Here, at StackOverflow, we can edit questions and answers. And then we can look at any revision of the question or answer we want. For example: [revisions](https://stackoverflow.com/posts/60174/revisions) of some random question. Maybe som...
In the past, I have used [diff-match-patch](https://code.google.com/p/google-diff-match-patch/) with excellent (and fast) results. It is available for several languages (my experience with it was in C#). I did not use it for exactly the process you are describing (we were interested in merging), but it seems to me you ...
i have similar issue in workplace. i implement the use of trigger after update to record all needed data to a another table (which of course you can save only the difference field only), and the new on exist on the real table, while the log live in another table.
How to keep updates (diffs) of some entity in the database
[ "", "mysql", "sql", "database", "postgresql", "" ]
I am using a mysql case for some calculation and my demand is that if the output is negative then i will show 0 in the place of the negative column.Otherwise the positive value. Let me post the query: ``` select concat(jo.title,' (', CCP.name, ')'), PL.analyst, PL.consultant, PL.csm, (CASE WH...
please check this, haven't tested yet. Note: this might not be the best solution ``` select concat(jo.title,' (', CCP.name, ')'), PL.analyst, PL.consultant, PL.csm, if( (CASE WHEN PL.productType like 'Staffing' THEN (SELECT ((DATEDIFF(PL.dateEnd, PL.dateClientEffective)) -((WEEK(PL.dateEnd) - WEEK(PL.dateClientEffe...
The simplest way is simply to use `greatest()`: ``` select greatest(<expression>, 0) as col ``` It is unclear what column/expression you want to do this for in your query. But, you can just plug it in. The advantage of this method over other methods is: * The only needs to appear once in the query. Not having to du...
How to check negative values in mysql and decide the output after that
[ "", "mysql", "sql", "" ]
I have a table which appears like this (I've shortened it for example purposes) ``` no no19 no68 3387034694344500 3387452540705400 3388486878919450 3371522572594880 3372232397709690 3373608476884750 ...
You could delete them in your UNION query like: ``` SELECT no FROM table WHERE no IS NOT NULL UNION SELECT no19 FROM table WHERE no19 IS NOT NULL UNION SELECT no68 FROM table where no68 IS NOT NULL ``` You could also use COALESCE() instead of union since a column only contains data when the other's are null: ``` SE...
Maybe something like this: ``` select isnull(no,'')+isnull(no19,'')+isnull(no68,''), a,b,c,d from book1 ``` That should concatenate all token in a row (and only one from no, no19 and no68 will have a value).
Union columns and remove blanks
[ "", "sql", "sql-server", "syntax", "" ]
I'm confused. How could you explain this diffenece in variable concatenation with ORDER BY? ``` declare @tbl table (id int); insert into @tbl values (1), (2), (3); declare @msg1 varchar(100) = '', @msg2 varchar(100) = '', @msg3 varchar(100) = '', @msg4 varchar(100) = ''; select @msg1 = @msg1 + cast(id as varc...
As many have confirmed, this is not the right way to concatenate all the rows in a column into a variable - even though in some cases it does "work". If you want to see some alternatives, please check out [this blog](http://www.sqlmatters.com/Articles/Converting%20row%20values%20in%20a%20table%20to%20a%20single%20conca...
SQL Server will calculate the results, then sort them, then return them. In the case of assigning a variable, only the first result will be used to populate your variable. You are receiving the first value from the sorted result sets, which can move around the order SQL Server will scan the records as well as the posit...
Using SQL concatenation with ORDER BY
[ "", "sql", "sql-server", "t-sql", "sql-server-2014", "" ]
Here is what I am trying to do: ``` IF len(Variable) > 1 BEGIN SELECT * INTO #TEMPTAB FROM multiple joins END ELSE BEGIN SELECT * INTO #TEMPTAB FROM different multiple joins END SELECT * FROM #TEMPTAB more large number of multiple joins & where & groupby ERROR: There is already an object #TEMPTAB defined -- ...
This was a fun problem for me that is... Well I figured out four ways to do it. One is with a view, one with a temp Table, one with a physical table, and one with a stored procedure and global temp table. Let me know if you have any questions. ## View ``` DECLARE @Variable VARCHAR(10) = 'aa'; IF LEN(@Variable) > 1 B...
Didn't you consider dynamic query with global temporary tables? This works for me: ``` DECLARE @sql NVARCHAR(MAX) = CASE WHEN 1 = 2 THEN 'SELECT * INTO ##TEMPTAB FROM dbo.SomeTable1' ELSE 'SELECT * INTO ##TEMPTAB FROM dbo.SomeTable2' ...
T-SQL If Else condition on the same Temp Table
[ "", "sql", "sql-server", "t-sql", "" ]
I have to create a SQL query to list all the Nurses in the ‘Sparrow’ Wing ordered by last name, first name. However, I need to pull Nurse\_name and Nurse\_surname from the Nurse table, which is linked to another table called Sister by the foreign key Sister\_ID, this table is then linked to another table called Wing w...
Since you seem to be aware that you should use the `inner join` to connect tables (but apparently not that the connection needs to be via the related columns) you should apply that knowledge to connect all the tables you need to answer the query. If you start at the end result and work your way backwards you first cho...
You don't give much information about the schema involved but maybe this will help: ``` select n.Nurse_name , n.Nurse_surname , w.Wing_name , managing_nurse.Nurse_name , managing_nurse.surname from Nurse n join Sister s on n.Sister_ID=n.Sister_ID join Wing w on s.Sister_ID=w.Sister_ID join Nurse managing_nur...
SQL query to pull data from three different tables
[ "", "sql", "oracle", "" ]
I'm trying to return information on cars in my table 'Cars' which have MOT's due within the next 2 weeks. MOTDUE has been defined as `to_date('2015-03-25', 'yyyy-mm-dd');` ``` SELECT * FROM Cars WHERE MOTDUE = CURRENT_DATE + INTERVAL '2' WEEK; ``` just gives me "missing or invalid datetime field" error. Thanks.
Depending on what you mean by "within the next two weeks" and assuming that the datatype of the `MOTDUE` column is `DATE`, then the following ought to give you what you need (or at least, allow you to amend appropriately): ``` select * from cars where motdue < trunc(sysdate) + 14 and motdue >= trunc(sysdate); ``...
There are two types of `INTERVAL`s in Oracle - `YEAR TO MONTH` and `DAY TO SECOND`. So `YEAR`, `MONTH`, `DAY`, `HOUR`, `MINUTE` and `SECOND` are all valid increments. `WEEK`, unfortunately, is not (nor is `FORTNIGHT`, sadly). The ANSI standard way of doing this would be something like the following: ``` SELECT * FROM ...
Oracle SQL Retrieve dates within 2 weeks
[ "", "sql", "oracle", "date", "" ]
I have SQL Server not Express and when db grows to 10240 I get error: > Could not allocate space for object in database because the 'PRIMARY' > filegroup is full. Create disk space by deleting unneeded files, > dropping objects in the filegroup, adding additional files to the > filegroup, or setting autogrowth on for ...
The instance name for SQL Server Express is by default `SQLEXPRESS` - but it can be anything you choose during installation. If you install SQL Server Express as the **default** (un-named) instance, then you get `MSSQLSERVER` as the pseudo instance name for SQL Server Express. Hence, you really cannot rely on the *ins...
I had the same error in my Express Edition as the official documentatios says, to fix it without shrink the DB I upgraded my version, from Express to Developer edition. Go to SQL Server Installation Center->Maintenance->Edition upgrade.
CREATE DATABASE or ALTER DATABASE failed because the resulting cumulative database size would exceed your licensed limit of 10240 MB per database
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have a model called Category that can have many subcategories (which are also Category records). I want to collect all Categories in the database that have no subcategories with something like: ``` Category.where(subcategories: []) ``` But every intuitive [to me] variation of this that I've tried either throws an e...
OK, solved. I just needed to tweak Sharvy's suggestion (one big thing I forgot is to add a "joins"). The following worked: ``` Category.includes(:subcategories).where(subcategories: nil) ``` **UPDATE 2:** OK, this time I *really* got it working (pretty sure, at least...). I had to use some ugly SQL rather than just ...
Try this: ``` Category.joins(:subcategories).where(subcategories: {parent_id: nil}) ``` or ``` Category.includes(:subcategories).where('subcategories.parent_id IS NULL') ```
How can I check for an empty association with a where statement in rails?
[ "", "sql", "ruby-on-rails", "where-clause", "" ]
The follow tables I have are: ``` CUSTOMERS (CustomerID, firstname, surname etc) ROOMS (RoomID, RoomType, Description) BOOKING (BookingID, CustomerID, Arrival Date, Departure Date, number of people, total cost) ROOMS_BOOKED (BookingID, RoomID) ``` The user enters two dates arrival and departure. Then checks for r...
You have the following cases ``` The user's selected period: --------[---------]------- Booking no1 [-----]------------------- Booking no2 --------------------[----] Booking no3 -----[----]--------------- Booking no4 -----------[---]---------- Booking no5 ------[-------]----------- Booking no6 --------------[--------...
this query list all rooms and for each room shows if it is available within [Arrival , Departure] dates ``` SELECT RoomType, case when NOT EXISTS (SELECT RoomID FROM ROOMS_BOOKED rb JOIN BOOKING b on b.BookingID = rb.BookingID WHERE rb.RoomID = r.Id ...
SQL query to search for room availability
[ "", "sql", "sql-server", "" ]
I'm looking for a way to select top 3 rows from 4 vendors from a table of products, following this criteria: 1. Must select 4 vendors. 2. Must select top 3 products for each vendor ordered by product rating. I tried doing something like: ``` select top 12 * product, vendor from products order by productrating ``` ...
You can use the ANSI standard `row_number()` function to get 3 products for each vendor: ``` select p.* from (select p.*, row_number() over (partition by vendor order by rating desc) as seqnum from products p ) p where p.seqnum <= 3 ``` If you want 4 vendors: ``` select top 12 p.* from (sele...
This will give you top 3 Products per vendor. You didn't specify how you're selecting the 4 vendors. That logic could easily be included using the WHERE clause or using a different ORDER BY depending on how you select the 4 vendors. ``` SELECT TOP 12 vnd.Vendor, apl.ProductName FROM Vendors vnd CROSS APPLY ( ...
SQL select x number of rows from table based on column value
[ "", "sql", "sql-server", "" ]
I have a query I don't really understand: ``` SELECT DISTINCT TBL.* FROM ( SELECT attribute1, attribute2, etc... FROM table) TBL ``` I'm guessing TBL is giving the result set a name, but why is it necessary in the select statement and what does the '.' do?
The dot `.` indicates that you are reffering to a column (or all columns) of the table TBL (in your case the subquery) The outer query just applies `DISTINCT` to every column of the inner query Note that in your case it doesn't make much sense to have a nested query, you can rewrite the query like this: ``` SELECT D...
In your example, there is no difference between `TBL.*` and `*`, but suppose your query was something like ``` Select * from Customer Inner Join Country on Country.ID = Customer.CountryID where Country.Code = 'UK' ``` This will return every column in **both** Customer and Country tables whereas ``` Select Cu...
Explain SQL Syntax: Select tbl.*
[ "", "sql", "syntax", "subquery", "" ]
I need a help in escaping single quotes in postgresql insert. I am using a ETL tool for data extraction from source and loading in a postgresql database.The Select statement includes some variables. For example My select query is ``` SELECT ${UNIVERSITY},date from education. ``` The variable `${UNIVERSITY}` has the ...
You can do `SELECT REPLACE(${UNIVERSITY},'''', ''''''),date from education.` But probably you just need to do `SELECT '${UNIVERSITY}',date from education` as your query looks like: ``` SELECT Duke's university,date from education ``` That is definitely wrong by SQL syntax.
Since you have mentioned it does not refer a column in the table education. You can achieve the same expected output through this transformation. ![enter image description here](https://i.stack.imgur.com/yGsir.png) Here in - `Table input` step you can write the query `SELECT date from education` - In `split fi...
Postgres SQL Single quote Escape
[ "", "sql", "postgresql", "pentaho", "" ]
Simple problem. I have a simple SQL as thus... ``` SELECT a.Col1, a.Col2, XXX FROM table1 AS a LEFT JOIN table2 as b ON b.Key1 = a.Key1 ``` What can I put in the 'XXX' above to say something like "does table B exists?". ie: `EXISTS(b) AS YesTable2` I am hoping there is a simpler solution than just using CASE....
You could use [ISNULL](https://msdn.microsoft.com/en-us/library/ms184325.aspx)(b.Key1, 'XXX') Or [COALESCE](https://msdn.microsoft.com/en-us/library/ms190349.aspx) for checking against multiple values for the first non null value.
Pick any column from `b` that is not allowed to be NULL. If there is a NULL there, the record does not exist. If there is a value there, the record does exist. If every column in `b` is allowed to be NULL (rare: you should always have something that's not nullable in the primary key) you'll have to build an expression ...
SQL: How to know if a LEFT JOIN returned a row?
[ "", "sql", "join", "" ]
Working in a school district I have a database that contains information about students' Education Plans. I'm using Management Studio to access a SQL Server 2012 database. I need to grab the information from their 2nd most recent plan. Here are the columns. * Database Name is `PlansAnoka` * Table name is `dbo.plans` ...
Use the `ROW_NUMBER` function and partition by `StudentID`: ``` WITH A AS ( SELECT StudentID , PlanDate , MeetingDate, ROW_NUMBER() OVER(PARTITION BY StudentID ORDER BY PlanDate DESC) rownum FROM dbo.plans ) SELECT * FROM a WHERE rownum=2 ```
use `row_number` if you want get `n'th` record: ``` select * from (select studentid , plandata , row_number() over(partition by plandata order by plandata desc) rn from dbo.plans) t where t.rn=2 -- or n ```
How to grab data from the 2nd most recent record for each student?
[ "", "sql", "sql-server-2012", "" ]
I want to group ids in my table in three groups and every day to select one of that group and repeat the cycle every 4th day. I don't know if I explained correctly but I will try to do it on an example. Let's say we have ids `1,2,3,4,5,6,7,8,9,10...n` The first day I want to select `1,4,7,10...n` the second day `2,5,8,...
Use the MOD(x,y) function which returns the remainder of x divided by y and the function TO\_DAYS(some\_date\_here) which returns the number of days since year 0. By using the function NOW() inside TO\_DAYS we get a new number every day. Put that in modulus also, and this will generate a cycle every 3 days that will se...
``` SELECT * FROM TABLE WHERE id%3 = 1 -- for day 1 id%3 = 2 -- for day 2 id%3 = 0 -- for day 3 ``` Or you can use: ``` SELECT * FROM TABLE WHERE CASE WHEN id % 3 = 0 THEN 3 ELSE id % 3 END = YourDayNumber ``` Sample: ``` SELECT id, 'Day ' + CAST(CASE WHEN id % 3 = 0 THEN 3 ...
Selecting from database with a sequence of three
[ "", "mysql", "sql", "math", "" ]
I'm trying to use CASE in a SELECT statement that will change two values of the possible 12 in a column. ``` CASE WHEN grade = 0 THEN 'R2' WHEN grade = -1 THEN 'R1' ELSE --ignore-- END AS "Grade level" ``` Does anyone have any idea what to replace the --ignore-- with, so that only those two possible values will be al...
Since grade is a number, you need to convert it to a character so it'll fit with `R1` and `R2`. ``` CASE WHEN grade = 0 THEN 'R2' WHEN grade = -1 THEN 'R1' ELSE to_char(grade) END AS "Grade level" ```
Just remove the `ELSE` part: ``` CASE WHEN grade = 0 THEN 'R2' WHEN grade = -1 THEN 'R1' END AS "Grade level" ```
CASE ... ELSE *ignore* in Oracle SQL
[ "", "sql", "oracle", "" ]
I am using a Select Query to insert data into a Temp Table .In the Select Query I am doing order by on two columns something like this ``` insert into #temp Select accnt_no,acct_name, start_date,end_date From table Order by start_date DESC,end_date DESC Select * from #temp ``` Here when there is an entry present ...
The 1/1/1900 usually comes from trying to cast an empty string into a datetime. Is your 'date' source column an actual datetime datatype or a string-ish varchar or char?
Sounds like the table definition requires that end\_date not be null, and has default values inserted automatically to prevent them. Are you sure there are even nulls when you do a straight select on the table without the confusion of ordering and inserting?
Order by on Two Datetime Fields .If one field is Null How to avoid Sybase from populating it with default datetime
[ "", "sql", "datetime", "sybase", "sap-ase", "" ]
I am attempting to modify the datatype of a specific column in a specific table in a SQL Server 2012 database. in the beginning of the script, the user will be setting the new desired length of the column datatype. However when I attempt to alter the column in the table to set the new `varchar` length I am getting an e...
if you want to be able to change the `length` of a `varchar column` `dynamically` then use `dynimic sql`, because `varchar(n)` does not allow parameters for `n`: ``` declare @sql varchar(500); Declare @newPrecis int Set @newPrecis = 23 --or any other value set @sql='Alter Table [dbo].[VTAB0047] Alter Column VAL varc...
``` Declare @newPrecis int Declare @query varchar(max) Set @newPrecis = 23; -- New length of the index set @query ='Alter Table [dbo].[VTAB0047] Alter COLUMN VAL varchar(' + Cast(@newPrecis as varchar) +')' exec (@query) ```
Define varchar with variable length
[ "", "sql", "sql-server", "t-sql", "varchar", "alter-table", "" ]
I'm trying to create trigger that checks if a phone number if in the (###) ###-#### format, if it this then nothing will happen, if is not then it will be fixed; however if there are more than 10 digits in the number then it will be turned to NULL. Unfortunately I keep getting the Invalid NEW or OLD specification erro...
There are several errors here; as others have said you need to explicitly use `:new.` and `:old.` to reference columns in your trigger, so `REGEXP_LIKE(vendor_phone` becomes `REGEXP_LIKE(:new.vendor_phone`. However, there are some more fundamental errors. 1. As with the [`LIKE` operator](http://docs.oracle.com/cd/E11...
You have to specify the :NEW whenever you are using the column names. try this: ``` CREATE OR REPLACE TRIGGER phone_correction BEFORE INSERT OR UPDATE OF vendor_phone ON vendors FOR EACH ROW WHEN (NEW.vendor_phone != REGEXP_LIKE(NEW.vendor_phone, '^\(\d{3}\) \d{3}-\d{4}$')) BEGIN IF :NEW.vendor_phone != REGEXP_L...
Invalid NEW or OLD specification error
[ "", "sql", "oracle", "triggers", "" ]
I am getting a problem with using 'Next Sequence Values' inside a procedure. I have my 'external' function to return the Next Value of Sequence. Inside my procedure, i want to assign the values of that sequence into a variable and use that variable inside my cursor (since i am using a union statement in my cursor). B...
The `raise_application_error()` procedure is an Oracle PL/SQL built-in. It's provided so what we can associate a custom message to a user-defined exception. User-defined exceptions must have numbers in the range -20999 to -20000. [Find out more](http://docs.oracle.com/database/121/LNPLS/errors.htm#LNPLS99960). You are...
The error number you pass to the raise\_application\_error procedure must be a negative integer in the range -20000..-20999. For user-defined exceptions SQLCODE returns always +1, so you're passing +1 as the error number to the raise\_application\_error procedure and that's out of range.
Assign function to a variable and use it within procedure
[ "", "sql", "oracle", "stored-procedures", "plsql", "" ]
This query returns the count for duplicate columns col B, col C, col D ``` SELECT `colB`, `colC`, `colD`, COUNT(1) as CNT FROM `table` GROUP BY `colB`, `colC`, `colD` HAVING COUNT(1) > 1 ``` How do I delete the duplicate records while keeping one ? ``` DELETE FROM `table` WHERE ( // Keep one record and delete row...
If you have a primary key, you can do: ``` delete t from table t left join (select cola, colb, colc, min(cola) as cola from table t group by cola, colb, colc ) tokeep on t.cola = tokeep.cola where tokeep.cola is null; ``` However, lots of deletes on a table can be inef...
try this ``` DELETE a FROM table a LEFT JOIN ( SELECT MIN(colA) colA , colB , colC ,colD FROM Table GROUP BY colB , colC,colD ) b ON a.colA = b.colA and a.colB = b.colB and a.colC = b.colC and a.colD = b.colD WHERE b.colA IS NULL ```
Mysql - Delete rows with duplicate columns
[ "", "sql", "" ]
I have two tables and I want to get the data from both tables. CustomerDetails ``` Id Customer1 Customer2 1 1 2 2 2 1 3 1 3 CustomerName Id Name 1 a 2 b 3 c ``` output should be ``` Id Customer1 Customer2 1 a b 2 b a 3 a c ``` I tried with inner join bu...
use **2** `join`s ``` select t1.id,t2.name customer1 ,t3.name customer2 from customerdetail t1 join customername t2 on t1.customer1=t2.id join customername t3 on t1.customer2=t3.id ```
``` SELECT Id, CN1.Name AS Name1, CN2.Name AS Name2 FROM CustomerDetails CD JOIN CustomerName AS CN1 ON CD.Customer1 = CN1.ID JOIN CustomerName AS CN2 ON CD.Customer2 = CN2.ID ``` I would do it with `LEFT JOIN` as it would be more safe. I do not know if you do have...
How To create correct Join between two tables?
[ "", "sql", "view", "sql-view", "" ]
In SQL Server Management Studio I can take database backups and save them as `.bak` files, which can also be restored in SQL Server Management Studio. Is there any difference between doing this and setting up a script which backs up the `.MDF` and `.LDF` files - and if there was ever an issue, I could just re-attach t...
It depends on your restore needs and backup space. It's certainly possible to to just reattach MDF and LDF files, but there are some limitations: * You have to detach the database first, make the backup (both files at the same time) and then reattach. This means downtime. * You cannot make incremental backups. * You c...
Database backups are much more powerful than backing up the files. First of all, if you backup the files while the database is in use, because it is changing constantly you may get something that works, or more likely you will get a corrupted file. A proper database backup coordinates ongoing changes with the backup p...
MDF and LDF SQL Server backups
[ "", "sql", "sql-server", "database-backups", "" ]
``` select application from l3_usage where function in ('dbms', 'web', 'app') group by application, function order by application ``` ![enter image description here](https://i.stack.imgur.com/70kFF.png) This is the result image when I execute the above query. I want to now count the number of times applicatio...
Try this query: ``` SELECT x.application, COUNT(*) As Frequency FROM ( SELECT application FROM l3_usage WHERE function IN ('dbms', 'web', 'app') GROUP BY application, function ORDER BY application ) AS x GROUP BY x.application HAVING COUNT(*) < 3 ORDER BY COUNT(*) ``` I query the result set you ...
``` SELECT application,COUNT(CASE WHEN application IS NOT NULL THEN 1 END) FROM table group by application ``` I found reference from [here](https://stackoverflow.com/a/8635631/2630817) ## Edit --- ``` select * from( SELECT typing,COUNT(CASE WHEN typing IS NOT NULL THEN ...
How to count distinct results from a already executed SQL Query?
[ "", "mysql", "sql", "oracle", "distinct", "" ]
I dont know how to call this topic so I thought I just would explain what I need. I have the following table: ``` Id IdPerson date successfully 1 1 01.01.2012 FALSE 2 1 01.01.2014 TRUE 3 2 01.01.2014 FALSE ``` Now I want all IdPerson where the newest entry is FALSE So that wo...
There is an interesting approach to this that uses conditional aggregation: ``` select idperson from table t group by idperson having max(date) = max(case when successfully = 'false' then date end); ``` Note: this solution (as well as the others) assume that `date` is stored in a native date/time format. If not, you ...
Use `ROW_NUMBER() OVER (PARTITION BY ...)` in a subquery to locate the newest entry per person. Then, in the outer query, select only those having `successfully = 'FALSE'`: ``` SELECT Id, IdPerson, [date] FROM ( SELECT ROW_NUMBER() OVER (PARTITION BY IdPerson ORDER BY [date] DESC) AS rn, * FROM MyTable ...
SQL compare two max Dates from the same table
[ "", "sql", "sql-server", "max", "" ]
I have a table `Retail` ``` CustomerID Itemset 1 31 1 30 1 78 2 31 2 91 3 30 3 31 ``` I want to to find the count of `CustomerID` having both `30` & `31` in `Itemset`. I.e. In this case `1` & ...
``` select count(*) from ( select CustomerId from Retail where Itemset in (30,31) group by CustomerId having count(distinct Itemset) = 2 -- this guarantees that CustomerId have at least one 30 and at least one 31 in column Itemset ) T ```
``` Select count(distinct(CustomerID)) from ( select r30.CustomerID from Retail r30 inner join Retail r31 on r31.CustomerID = r30.CustomerID where r30.Itemset = 30 and r31.Itemset = 31 ) T ```
How to formulate this SQL Query
[ "", "sql", "sql-server", "" ]
My original table is this; TableName= NewRetail ``` CustomerID 1 2 3 4 5 6 7.....30 1 30 31 Null Null Null Null Null 2 24 78 35 72 Null Null Null ``` I want to store this table in 'Retail' `CustomerId Itemset 1 30 1 31 2 24 2 78 2 35 2 72` There are no ...
You can do this using `UNION ALL`: ``` SELECT * FROM ( SELECT CustomerId, [1] AS ItemSet FROM NewRetail UNION ALL SELECT CustomerId, [2] FROM NewRetail UNION ALL SELECT CustomerId, [3] FROM NewRetail UNION ALL SELECT CustomerId, [4] FROM NewRetail UNION ALL SELECT CustomerId, [5] FROM NewRetail UNI...
You can use `table valued constructor` with `Cross apply` to `unpivot` the data ``` SELECT CustomerID, Itemset FROM Yourtable CROSS apply (VALUES ([1]),([2]),([3]),([4]),([5]),([6]),([7]),...) cs (Itemset) WHERE Itemset IS NOT NULL ``` **Dynamic Version** ``` DECLARE @itemset VARCHAR(max)='', ...
How to merge column this specific way in SQL
[ "", "sql", "sql-server", "" ]
I am trying to build a SQL query where I group by 1 column, but then also include the values of other columns from an arbitrary record in each group. So, something like ``` SELECT BoxNo FROM MuffinData WHERE FrostingTimeApplied >= CONVERT(date, GETDATE()) GROUP BY BoxNo ``` but including some value from columns `M...
You have to use an aggregate function for each column selected that is not present in the `GROUP BY` clause: ``` SELECT BoxNo, MAX(MuffinType) AS MuffinType, MAX(FrostingType) AS FrostingType FROM MuffinData WHERE FrostingTimeApplied >= CONVERT(date, GETDATE()) GROUP BY BoxNo ``` If there is only 1 value of `Muffi...
> I know that there will be only 1 value of MuffinType and FrostingType > per box If that's indeed the case, a simple DISTINCT should do the trick, like so: ``` SELECT DISTINCT BoxNo, MuffinType, FrostingType FROM MuffinData WHERE FrostingTimeApplied >= CONVERT(date, GETDATE()); ``` If that's not the case, you're d...
SQL group by 1 column but include TOP 1 of other columns
[ "", "sql", "sql-server", "t-sql", "group-by", "" ]
I have the following data table. ``` Record Date Price A 3/1/2015 5 A 3/2/2015 6 A 3/3/2015 7 A 3/4/2015 10 B 2/1/2015 4 B 2/2/2015 6 B 2/3/2015 15 B 2/4/2015 2 ``` How can I output a table that only shows the First price...
Perhaps something like this is what you are looking for? ``` select R.Record, FD.Price as MinPrice, LD.Price as MaxPrice from Records R join ( select Price, R1.Record from Records R1 where Date = (select MIN(DATE) from Records R2 where R2.Record = R1.Record) ) FD on FD.Record = R.Record join ( select ...
Get the min and max aggregate dates grouped by the record field and join back to the root data. If you can have multiple records for the same record field on the same date, you will have to use min, max or avg to get just one value for that date. SQLFiddle: <http://sqlfiddle.com/#!9/1158b/3> ``` SELECT anchorData.Rec...
How to Obtain First and Last record ? One Step Solution?
[ "", "mysql", "sql", "where-clause", "" ]
I have problem with one query. This work: ``` select coalesce(((SUM(ati.anDebit) - SUM(ati.ancredit))),0) + (select coalesce((SUM(anDebit)),0) from tHE_AcctTransItem where acLinkDoc = '15-390-000523' and SUBSTRING(acDoc,4,3) in ('391', '3B0') and SUBSTRING(acKey, 3, 3) = '420' and acSub...
First, your SQL has a lot of extra parentheses, which along with the rather haphazard formatting makes it very hard to read and debug. Aggregate functions in the select clause of a query that does not have a group by clause will return a null record. ``` declare @t table ( k nvarchar(50), val int ) select su...
Logically, if your first query returns results and the third query does not, then the difference must be causing the issue. Notice that your subquery in the first query, is not correlated to the main from and where clauses. Try this query. I would ``` SELECT at.acDocType , ati.acDoc , ati.acKey , ...
T-SQL - empty CASE + select
[ "", "sql", "t-sql", "" ]
I have a table test which has ticket and vehcile. ``` ticket vehicle 1000 101 1001 102 1002 102 1003 103 1004 104 1005 102 1006 102 ``` My requirement: Input will be ticket and ouput will be vehicle.If the vehcile is repeating then I have to get just the previous ticket. **For example:** ticket...
[SQL Fiddle](http://sqlfiddle.com/#!6/ca9cd/19) **MS SQL Server 2014 Schema Setup**: ``` create table test( ticket int,vehicle int); insert into test values(1000,101); insert into test values(1001,102); insert into test values(1002,102); insert into test values(1003,103); insert into test values(1004,104)...
<http://sqlfiddle.com/#!6/ca9cd/22> ``` DECLARE @ticket int = 1006 select MAX(prev.ticket) from test curr inner join test prev on curr.vehicle = prev.vehicle AND curr.ticket > prev.ticket where curr.ticket = @ticket ```
How to get just upper value based on column
[ "", "sql", "sql-server", "sql-server-2012", "" ]
I have a table in SQL say like the following: ``` -------------------------- |ID | number| numberDate | |---|-------|------------- | 1 | 120 | 2011-01-22 | |---|-------|------------| | 1 | 124 | 2011-01-27 | |---|-------|------------| | 2 | 136 | 2011-01-20 | |---|-------|------------| | 2 | 135 | 2011-01-30 |...
We'll do this in two steps. ``` --Step 1: Find records the violate the rule With BadIDs AS ( --IDs where there is another record with a matching ID and lower number, but greater date select t1.id from [table] t1 inner join [table] t2 on t2.id = t1.id where t1.number > t2.number and t1.numberDate <...
you can use a `where exists...subquery`. this query should give you all id's have increasing number: ``` select distinct t.id from table_name t where exists ( select t2.number from table_name t2 where t2.id=t.id and t2.number > t.number ) ```
How to SELECT (SQL) items only if they are in increasing order?
[ "", "mysql", "sql", "" ]
I created new tables `Faculty` and `Specialty` as described in the link below, but I do not see them under databases in the Object Explorer. Also, if I click on 'edit', I do not see 'Intellisense' anywhere. What is going on? <http://www.cs.trinity.edu/~thicks/Tutorials/MSSQL-Server-Management-Studio-DB-Construction/MS...
Check Refreshing the database in object explorer. ![image](https://i.stack.imgur.com/vte34.gif)
Simply go your database and write this query: ``` USE DBName --Change the database name in which you have created your table GO IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'TheSchema' AND TABLE_NAME = 'Faculty')) BEGIN print 'table exists' EN...
Saved table not showing up in Object Exploer in SQL Management Studio
[ "", "sql", "ssms", "" ]
I have some issues when I want to select some rows after joining two tables. I have 3 tables, Library can contains multiple books, Books belong to one or more Library and have a BookTypeId for each language the book is available. ``` Library Id|Name Books Id|IsAvailable|LibraryId|BookTypeId BookType Id|DisplayName|...
Your WHERE condition cannot be satisfied. Modify that. Maybe you mean OR? ``` WHERE (BookType.Language='Bookname1_FR' AND Books.IsAvailable='1') OR (BookType.Language='Bookname2_EN' AND Books.IsAvailable='1') ``` UPDATED: you should use GROUP BY for your requirement ``` SELECT l.Id, l.Name, BookType.Language FROM [L...
``` SELECT l.Id, l.Name, BookType.TypeName, Books.IsAvailable FROM [Library] l RIGHT JOIN Books ON l.Id = Books.LibraryId LEFT JOIN BookType ON Books.BookTypeId = BookType.Id WHERE (BookType.Language='Bookname1_FR' AND Books.IsAvailable='1') AND (BookType.Language='Bookname2_EN' AND Books.IsAvailable=...
SQL select issues after join
[ "", "sql", "sql-server", "t-sql", "join", "" ]
I am trying to get around an apparently simple problem in MySQL: I have a table composed by 3 fields and I would like to form a query that returns a field selected as DISTINCT and two more columns which return a COUNT of the remaining two fields when a specific condition is met. To illustrate (columns named *first*, *...
You can simply use this query : ``` select first , SUM(IF(third=0,1,0)) as Col_zero, SUM(IF(third=1,1,0)) as Col_one from table group by first; ```
You can use `UNION` in following: ``` SELECT first AS field_one, COUNT(second) FROM table WHERE third = 0 GROUP BY field_one; UNION SELECT first AS field_one, COUNT(second) FROM table WHERE third = 1 GROUP BY field_one; ``` --- Also how about `IN`? ``` SELECT DISTINCT(first) AS field_one, ...
MySQL - Conditional SELECT to output separate columns
[ "", "mysql", "sql", "database", "conditional-statements", "" ]
I have 2 table, but I wanted to query the 'rejected' status only, means I need query the result that the **user has only rejected status**, instead of having **approve** **&** **reject,** or **approve** in submissions table ``` Users Table ----------- id | name ----------- 1 | John 2 | Doe 3 | Testing 4 | Sample ...
I found a solution already which is using `WHERE NOT EXISTS` to filter the `approved` result in submission ``` SELECT u.id AS user_id,s.*, u.name FROM submissions s LEFT OUTER JOIN users u ON s.user_id = u.id WHERE NOT EXISTS ( SELECT USER_ID FROM submissions tmp WHERE tmp.User_ID = s.User_ID AND tmp....
Why did you use left outer join ? I believe simple join will get you the result .. ``` SELECT u.id AS user_id,s.*, u.name FROM submissions s JOIN users u ON s.user_id = u.id AND s.status = 'rejected' ``` OR ``` SELECT u.id AS user_id,s.*, u.name FROM submissions s JOIN users u ON s.user_id = u.id WHERE s.status = '...
Select certain value only
[ "", "mysql", "sql", "sqlyog", "" ]
I have a table which holds a set of records. Now through SQL I am getting a Count for each different status. Example from the table below: ``` Status | ID ------------------------- Open | 1 Open | 2 Open | 3 Open | 4 In Progress | 5 In Progress | 6 In Pr...
``` SELECT CASE WHEN Status = 'Closed' THEN Status ELSE 'OTHER' END AS Status, Count(job) As CountJobs FROM JobsTable GROUP BY CASE WHEN Status = 'Closed' THEN Status ELSE 'OTHER' END ORDER BY CountJobs DESC ```
Use a `CASE` expression: ``` SELECT CASE WHEN myStatus = 'Closed' THEN 'Closed' ELSE 'Other' END myStatus, COUNT(*) CountJobs FROM JobsTable GROUP BY CASE WHEN myStatus = 'Closed' THEN 'Closed' ELSE 'Other' END; ```
SQL Query to get count of one status + all other status as one
[ "", "sql", "sql-server", "database", "t-sql", "" ]
I have a query: ``` SELECT s.period, s.year, s.amount FROM salaries s ``` I would like to select from `salaries` table only the rows that have period and year equal to: ``` SELECT p.period, p.years FROM periods p ``` I know that the simplest way would be use join, but the problem is - that in the application I ca...
You can use more than one column for an `IN` condition: ``` SELECT s.period, s.year, s.amount FROM salaries s where (s.year, s.period) in (select year, period from periods) ``` But Gordon's `not exists` solution is probably faster.
Does this work with your environment? ``` WHERE EXISTS (SELECT 1 FROM periods p WHERE p.period = s.period AND p.year = s.year ) ```
Two columns in subquery in where clause
[ "", "sql", "postgresql", "" ]
Following are the tables from my database: ![enter image description here](https://i.stack.imgur.com/GdHm3.png) I need following columns from the above tables as follows : **tblVendor :** `Name` (AS `VendorName`) **tblVendorItem :** `Name` ( AS `VendorItemName`) **tblEvent :** `Name`( AS `EventName`) and `EventDat...
Your forgot to join table "tblVendorItem" ``` SELECT tblEvent.NAME AS 'EventName', tblEvent.EventDate AS 'EventDate', tblVendorItem.NAME AS 'VendorItem', tblVendor.NAME AS 'VendorName', tblEventService.ServiceDate AS 'Date', tblEventServic...
As suggested, use aliases when joining the same table, like this: ``` SELECT es1.EventID FROM tblEventServices es1 JOIN tblEventServices es2 ON es1.EventID = es2.EventID --or however you wish to join them ```
Multiple inner joins returning Error
[ "", "sql", "sql-server", "" ]
I'm trying to select all the users in a table that have the same `Email` but have a different `Name`. So far I have managed to get all the rows that have duplicate `Email` but I'm stuck on the next step. ``` SELECT * FROM users WHERE Email IN (SELECT Email FROM users GROUP BY Email HAVING COUNT(*) > 1) ``` Thanks in ...
I think you just want `count(distinct name)` in the subquery: ``` SELECT * FROM users WHERE Email IN (SELECT Email FROM users GROUP BY Email HAVING COUNT(distinct Name) > 1 ) ; ``` I prefer `having min(name) <> max(name)` for the `having` clause. It is sl...
Try this ``` SELECT * FROM users U1 INNER JOIN users U2 on U1.Email=U2.Email AND U1.Name <> U2.Name ```
SQL - Select all rows that have the same Email but different Name
[ "", "sql", "select", "count", "group-by", "duplicates", "" ]
Consider the following numbers. ``` 7870.2 8220.0 ``` I need to remove decimal points if the value ends with `.0`. If it ends with `.2` then it should keep the value as it is. I have used `ceiling` but it removes all the values after decimal. How can I write a select query in which I can add some condition for this...
use `right` within a `case` statement and: ``` DECLARE @val decimal(5,1) SET @val = 7870.0 Select Case When right(@val,1)<> '0' then cast(@val as varchar) else cast(cast(@val as int) as varchar) End ``` **output:** 7870 **EDIT:** I could write : ``` Case When right(@val,1)<> '0' the...
Generally speaking you should *not* do this in your dB. This is an app or reporting side operation. The dB is made to store and query information. It is not made to format/string manipulate information.
Remove only zero after decimal sql server 2012
[ "", "sql", "sql-server", "sql-server-2012", "rounding", "" ]
I'm building a system where I have to find the combined price of a computer system by using the database data. The first screenshot is a build from the system table. **Systems Table** ![enter image description here](https://i.stack.imgur.com/Cl4nF.png) **Parts Table** ![enter image description here](https://i.stack....
There's a neat trick for unpivot in Postgres [using UNNEST( ARRAY( ...) )](https://stackoverflow.com/questions/1128737/unpivot-and-postgresql) This efficiently (in one pass of the table) unpivots those multiple columns of table computer\_system into multiple rows of (in this case) 3 columns: "nome", "colkind" and "col...
I Think you need break down your table design into 3 table, there are Component, Computer\_System and Computer\_component. Below are the field list: Computer\_System -> computer\_id and name Component -> nome\_component, kind, price Computer\_Component -> computer\_id, nome\_component. With that table, you can sum the ...
Transform database columns to rows and sum
[ "", "sql", "postgresql", "" ]
**Table Definition:** ``` CREATE TABLE [dbo].[tbl]( [Id1] [int] NOT NULL, [Id2] [int] NOT NULL, [Id3] [int] NOT NULL, [IsActive] [bit] NOT NULL, [CreatedTs] [datetime] NOT NULL, CONSTRAINT [PK_tbl] PRIMARY KEY CLUSTERED ( [Id1] ASC, [Id2] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE...
The problem is that dropping the PK constraint also drops the underlying clustered index, and heaps are not permitted in Azure. The best you can do is to create a new table with desired structure, copy the data over, drop the old table, rename the new one and recreate the FKs if any.
Azure SQL Database's latest update (V12) allows you to have tables without clustered indexes (i.e. as heaps). If you upgrade your server to the latest version, you'll be able to run your queries to modify the PK successfully. Other features enabled by V12: <http://azure.microsoft.com/en-us/documentation/articles/sql-d...
Unable to alter the Composite Primary Key in Azure Sql
[ "", "sql", "sql-server", "azure", "azure-sql-database", "composite-key", "" ]
I have a table. ``` select * from Group ``` ``` Owner Member1 Member1_Value Member2 Member2_Value Kelly Nicol 2 Julie 4 Nicol Julie 4 Kelly 3 Julie Kelly 5 Nicol 3 ``` Now I need to get Avege value from our Members for Ow...
I would say that what you want is this but you should consider normalising a little bit that table in order to be able to do this kinds of queries easier: ``` SELECT Name, AVG(Value) AS Value FROM ( SELECT Member1 AS Name, Member1_Value As Value FROM Group UNION ALL SELECT Membe...
If I understood it correctly then it should work : ``` select *, cast((Member1_Value + Member2_Value) as Decimal(10,2))/2 [Avg] from Group ```
SQL - get row for same table
[ "", "sql", "sql-server", "database", "stored-procedures", "sql-server-2008-r2", "" ]
I set **two user-defined variables** as shown below but after some time, I forgot the names: ``` SET @a = 2, @b = 3; ``` So, does MySQL have the command that displays **all user-defined variables**?
Starting with MySQL 5.7, the performance schema exposes user variables. See table `performance_schema.user_variables_by_thread` <https://dev.mysql.com/doc/refman/5.7/en/performance-schema-user-variable-tables.html>
If you have MariaDB (a binary "drop-in" equivalent of MySQL) there is a plugin available, provided by MariaDB itself. MariaDB 10.2 (equivalent to MySQL 5.7) and above has a plugin that creates a ["USER\_VARIABLES" table](https://mariadb.com/kb/en/library/information-schema-user_variables-table/). Here is how to [ins...
How to show all user-defined variables (MySQL)
[ "", "mysql", "sql", "database", "command-line", "mysql-variables", "" ]
i have table with DOB column ('2012-05-29 00:00:00.000') and few other fields , i need to select the data for DOB between 6 months to 6 Years. I tried using the below SQL but this is not giving me the right data. any help will be appreciated. ``` select * from dbo.xyz where ( FLOOR(DATEDIFF(MONTH, birth_date , GETDATE...
Try this ``` select * from dbo.xyz where DATEDIFF(MONTH, birth_date , GETDATE()) between 6 and 72 ```
When using dates, the advice is to use functions only on the non-column values. In other words, modify `getdate()`, not `birth_date`: ``` select * from dbo.xyz where birth_date between dateadd(year, -6, getdate()) and dateadd(month, -6, getdate()) ``` This has two advantages. First, it makes the `where` clause "sarg...
select month and year from Date of birth IN sql
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "ssms", "" ]
I'm trying to run an alter table query to add columns to an existing table: ``` ALTER TABLE dbo.Names Add solCorporate bit null ``` When I execute it just sticks in the executing query cycle, I've left it for 20 mins and nothing. Any ideas? I'm presuming if there was a code error it would flag before running. Thank...
I ran into the same problem today. I tried to stop the database connection by right-clicking it and choosing Stop (in the Object Explorer in MS SQL Server Management Studio). When that didn't help I launched Sql Server Configuration Manager and restarted the SQL Server from the SQL Server Services tab. After that, Alt...
Closing SQL server management studio worked for me
SQL alter table query stuck in execute
[ "", "sql", "sql-server-2008", "alter-table", "" ]
We imported a lot of data from another table. Now I'm trying to correct some of them. ``` UPDATE [x10ddata].[dbo].[ResourceTest] SET [Country] = (CASE WHEN [Country] IN ('Aezerbaijan', 'AZERBIJAN') THEN 'Azerbaijan' WHEN [Country] = 'Belgique' THEN 'Belgium' WHEN [Country] = 'China (RPC)' THEN '...
The `case` statement will return `null` if none of the `when` clauses are met. You can verify this with this simple sql: ``` declare @i int set @i = 2 select case when @i = 1 then 'A' end AS Column1 ``` This will return `null` since `@i` is not `1`. To fix this in your case, you can either add the `where` clause lik...
You won't need a WHERE clause, but the ELSE clause is needed. Change your statement to: ``` UPDATE [x10ddata].[dbo].[ResourceTest] SET [Country] = (CASE WHEN [Country] IN ('Aezerbaijan', 'AZERBIJAN') THEN 'Azerbaijan' WHEN [Country] = 'Belgique' THEN 'Belgium' WHEN [Country] = 'China (RPC)' THEN...
Do I need a where clause in a conditional UPDATE?
[ "", "sql", "sql-server", "t-sql", "" ]
I'm using PostgreSQL 9.3. I want to duplicate some of the db records. Since I'm using an auto-increment pk id for the table, I want to get back the id mappings from the generated ids of duplicated records to the original ones. For example, say I have a table `posts` with 2 records in it: ``` [{'id': 1, 'title': 'fir...
This would be simpler for `UPDATE`, where additional rows joined into the update are visible to the `RETURNING` clause: * [Return pre-UPDATE column values using SQL only](https://stackoverflow.com/questions/7923237/return-pre-update-column-values-using-sql-only-postgresql-version/7927957#7927957) The same is currentl...
if `id` column of `posts` is `serial` type, it's generated like `nextval('posts_id_seq'::regclass)`, you can manually call this function for every new row ``` with sel as ( SELECT id, title, nextval('posts_id_seq'::regclass) new_id FROM posts WHERE id IN (1,2) ), ins as ( INSERT INTO posts (id, title) SEL...
INSERT INTO ... FROM SELECT ... RETURNING id mappings
[ "", "sql", "postgresql", "sql-insert", "sql-returning", "" ]
Which would be the best way to get the number of people hired on each day of the week for 7 years from a table People that has their entry\_date with a day-month-year as 01-Jun-91. For example: ``` 2000 2001 2002 etc.. SUN 2 0 1 MON 0 0 2 ``` Do I have to create a counter for each day of each y...
You need to join each day of the week with your entry\_date and [pivot](http://oracle-base.com/articles/11g/pivot-and-unpivot-operators-11gr1.php) the results. [SQL Fiddle](http://sqlfiddle.com/#!4/a72667/24) **Query**: ``` with x(days) as ( select 'sunday' from dual union all select 'monday' from dual union all...
Depending on the version of Oracle you're using (10g doesn't have the `PIVOT` function, for example), you might try something like the following conditional aggregation: ``` SELECT day_abbrev , SUM(CASE WHEN year_num = 2000 THEN person_cnt ELSE 0 END) AS "2000" , SUM(CASE WHEN year_num = 2001 THEN person_cnt...
Get collection of integers from counter
[ "", "sql", "oracle", "" ]
Database: ``` Department Position Points A Manager 50 A Supervisor 10 A Supervisor 10 A Staff 2 A Staff 2 B Manager 40 B SuperVisor 8 ...
Use `Conditional Aggregate` to count only the specific data ``` Select Department, count(case when Position = 'Manager' then 1 END) as Manager, count(case when Position = 'Supervisor' then 1 END) as Supervisor, count(case when Position = 'Staff' then 1 END) as Staff From yourtable Group by Departm...
Use conditional `SUM`: ``` SELECT Department, SUM(CASE WHEN Position = 'Manager' THEN 1 END) as Manager, SUM(CASE WHEN Position = 'Supervisor' THEN 1 END) as Supervisor, SUM(CASE WHEN Position = 'Staff' THEN 1 END) as Staff FROM yourtable GROUP BY Department ```
Count without nested select: is this possible?
[ "", "sql", "count", "sql-optimization", "" ]
I have a dataset like this: ``` +---------+--------+--------+ | Student | Score1 | Score2 | +---------+--------+--------+ | 1 | 23 | 40 | | 2 | 12 | 10 | | 3 | 54 | 90 | +---------+--------+--------+ ``` I want to calculate the mean of the 2 scores on each row. In theory this...
Your method is a good one. I would write it as: ``` select student, ((coalesce(score1, 0) + coalesce(score2, 0)) / nullif(nvl2(score1, 1, 0) + nvl2(score2, 1, 0), 0) ) as score_avg ``` The advantage of this method (or the method in your question) is that it is easy to add more scores. That said...
what about this: ``` select student, case when score1 is null and score2 is not null then score2 when score1 is not null and score2 is null then score1 when score1 is null and score2 is null then 0 else (score1 + score2)/2 end from your_table ```
Can you run Oracle's AVG() function on values in the same row?
[ "", "sql", "oracle", "average", "" ]
I am in an argument with a friend of mine on how to store a small array (<10) of references in SQL. Lets say there is a class **player** which can hold **one** **item** in it's inventory. Describing this as an SQL table would be fairly straight forward: ``` CREATE TABLE items( id INT NOT NULL AUTO_INCREMENT...
This might make a good interview question. 1. Preference is opinon. It depends. However I avoid the "multiple columns" technique (technique #2) if I have more than 2 items per player for many many reasons. For one, if you design and code n=10 items per player, how many items will the project manager want tomorrow? n+1...
Make another table. Yes, making multiple columns violates 1NF. Why should you obey this rule? Consider: (1) Is the limit of 10 absolute? It sounds like this is some sort of game (from the word "player") so maybe it is. But in most applications, such limits tend to be of the "I can't imagine anyone ever having more th...
Store small array as multiple columns in SQL
[ "", "mysql", "sql", "database-design", "" ]
I am trying to write a simple Database application in go which access multiple data servers, some MySQL, MSSQL and SqlLite3. I am using the "database/sql" package to access them. ``` db, err := sql.Open(driver, dataSourceName) result, err := db.Exec( "INSERT INTO users (name, age) VALUES (?, ?)", "gopher", ...
Assuming that you don't want to use the servers logging facilities, the obvious solution would be to simply log all queries as they are made. ``` db, err := sql.Open(driver, dataSourceName) log.Println(dataSourceName, "INSERT INTO users (name, age) VALUES (?, ?)", "gopher", 27) result, err := db.Exec( "INSERT INTO...
There is now a solution for that without having to wrap `sql.DB` with a wrapper that adds the logging. [sqldblogger](https://pkg.go.dev/github.com/simukti/sqldb-logger) facilitates this without needing to change existing `sql.DB` code.
How to log queries to database drivers?
[ "", "sql", "database", "logging", "go", "" ]
I have the following table: ``` oGroup oDate oValue -------------------------------- A 2014-01-01 20 A 2014-01-02 30 B 2014-01-01 5 B 2014-01-02 15 C 2014-01-01 40 C 2014-01-02 60 ``` I want to have the following result: ``` o...
Learn on [Pivot](http://blog.sqlauthority.com/2008/06/07/sql-server-pivot-and-unpivot-table-examples/) ``` select * from piv pivot ( min(oValue) for oDate in([2014-01-01],[2014-01-02]) )as pivv; ``` Using `Dynamic sql` ``` declare @query nvarchar(max) declare @cols nvarchar(max) select @cols=stuff((select distinct ...
You could use [**dynamic crosstab**](http://www.sqlservercentral.com/articles/Crosstab/65048/): ``` DECLARE @sql1 VARCHAR(4000) = '', @sql2 VARCHAR(4000) = '', @sql3 VARCHAR(4000) = '' SELECT @sql1 = 'SELECT oGroup' + CHAR(10) SELECT @sql2 = @sql2 + ' ,MAX(CASE WHEN oDate = CAST(''' + CONVE...
Transpose row to column in SQL Server 2008
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have an order table which has the customer id and order amount. I want to join these orders but joined orders cannot exceed a certain amount. An example below: Let's say the maximum amount is 33 pallets and I have a table like this: ``` Order ID Client ID Amount 1 100001 10 2 1...
you can find proposed solution (sql definition) with help of recursive CTE here: <http://sqlfiddle.com/#!6/285c16/45> basicaly CTE iterates ordered list (by clientID, orderID) and evaluate if summed amount is not over 33. i have added next clientID to mock data, to test correct subcount criteria evaluation. here is ...
I tried to solve with simple selects and without using an explicit cursor but it was a little hard in that way. I've solved it and got exactly what you wanted with: a `TempTable`, a `cursor`, a `counter` for checking the sum of sequent amounts, `CHAR()` function to generate letters; I calculated the values and inserted...
SQL Group By Certain Amounts
[ "", "sql", "algorithm", "t-sql", "sql-server-2014", "" ]
I have the following table: ``` -------------------------------------------- Group Date Value1 Value2 Value3 -------------------------------------------- A 2014-01-01 10 10 5 B 2014-01-01 12 20 25 C 2014-01-01 20 40 50 ``` I want to have the fo...
For interchanging rows and columns, you need to `UNPIVOT`(convert columns into row values) first and then `PIVOT`(rows to columns) based on `UNPIVOT` result. ``` -- Here is the result SELECT * FROM ( -- Unpivot here using CROSS APPLY SELECT [Group], [Values],COLNAMES FROM YOURTABLE CROSS APPLY(V...
You can use the PIVOT operator. See the details below: ``` select 'Value1' NewCol, A, B, C from (select [Group], Value1 Value from YourTable) g pivot ( max(g.Value) for g.[Group] in (A, B, C)) p union all select 'Value2', A, B, C from (select [Group], Value2 Value from YourTable) g pivot ( max(g.Value) for g.[...
Column to Row SQL syntax
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have 3 tables ``` order (customerID, productID) product (productID, prodName, classID) classification (classID, className) ``` I need to get prodName and className where customerID=5555 ``` SELECT prodName FROM product AND className FROM classification LEFT JOIN order WHERE order.customerID=12345 ``` It's not wor...
You need to specify what field the join is on, like this: ``` SELECT prodName FROM product AND className FROM classification LEFT JOIN order ON classification.productID = order.productID WHERE order.customerID=12345 ```
Your syntax is a little off; ``` SELECT prodName FROM product ,classification LEFT JOIN order ON(classification.classID = order.classID) WHERE order.customerID = 12345 and order.productID = product.productID ``` That will return your Prod Name. Have to be honest, I'm not sure why you're doing a left jo...
joining/searching 3 tables
[ "", "sql", "left-join", "" ]
I've got this table, ``` Name Rating A 2 B 1 C 5 D 3 E 1 F 4 ``` and I've got a rating system ``` 1-Excellent, 2-Very Good, 3-Good, 4-OK, 5-Poor ``` I was wondering if i could replace the nueric values in the table to get the following result ...
Use a `CASE` statement. Of course, this will only work if your column is not set to a numeric value. ``` UPDATE tblRatings SET Rating = CASE WHEN 1 THEN 'Excellent' WHEN 2 THEN 'Very Good' WHEN 3 THEN 'Good' WHEN 4 THEN 'OK' ELSE 'Poor' ...
I don't think it's good idea to update your data inplace, it's better to store id of the rating and not text representation of the data. But you can query your table and replace int with text: ``` select Name, case Rating when 1 then 'Excellent' when 2 then 'Very Good,' when 3 then 'Goo...
Replace column values
[ "", "sql", "sql-server", "" ]
Let's cut to the chase. I have a table which looks like this one (using SQL Server 2014): **DEMO:** **<http://sqlfiddle.com/#!6/75f4a/1/0>** ``` CREATE TABLE TAB ( DT datetime, VALUE float ); INSERT INTO TAB VALUES ('2015-05-01 06:00:00', 12), ('2015-05-01 06:20:00', 10), ('2015-05-01 06:40:00', 11), ('2015-...
One way is to use the set with minimum hourly values as a derived table and join against that. I would do something like this: ``` ;WITH CTE AS ( SELECT Cast(Format(DT, 'yyyy-MM-dd HH:00') AS datetime) AS DT, SUM(VALUE) AS VAL FROM TAB GROUP BY Format(DT, 'yyyy-MM-dd HH:00') ) SELECT b.dt "Date", val "su...
``` DECLARE @TAB TABLE ( DT DATETIME , VALUE FLOAT ); INSERT INTO @TAB VALUES ( '2015-05-01 06:00:00', 12 ), ( '2015-05-01 06:20:00', 10 ), ( '2015-05-01 06:40:00', 11 ), ( '2015-05-01 07:00:00', 14 ), ( '2015-05-01 07:20:00', 15 ), ( '2015-05-01 07:40:00',...
SQL query - Find daily MIN value from hourly sums
[ "", "sql", "sql-server", "t-sql", "" ]
I need to write an SQL query to combine two tables... ``` Table: names +-------------+---------------+ | id | Name | +-------------+---------------+ | 1 | Bob | | 2 | Geoff | | 3 | Jim | +-------------+---------------+ Table: attributes +----...
``` SELECT n.name, a.attribute from names n cross join attributes a ``` The same can be achieved with following query: ``` SELECT n.name, a.attribute from names n join attributes a ON 1=1 ``` The only thing is that you show id from 1 to 9 in the output but there are no such IDs in the sample data. But if you have ta...
If you want to get an incremented id, just use a variable: ``` select (@rn := @rn + 1) as id, n.name, a.attribute from names n cross join attributes a cross join (select @rn := 0) vars; ```
How can I combine these two tables in SQL so that each row of the first has a copy of every row in the second?
[ "", "mysql", "sql", "" ]
If I had a table with 3 columns, `Column A` `Column B` and `Column C`. is the query faster if my select statement is like `Select Column A, Column B, Column C from Table`? what if it's `Select Column A, Column C, Column B from Table`? Same for update and insert. `Update Table set Column A = '', Column B = '', Column...
I don't believe *any* of the SQL standards dictate the performance requirements of individual statements so it's really totally under the control of the implementation. However, I'd be *very* surprised if there was a substantial difference since the bulk of the time would be simply retrieving the data and delivering i...
No, not in the SELECT or UPDATE columns. Places where order MIGHT matter are the GROUP BY/ORDER BY clauses. Predicates in the WHERE clause and JOIN conditions will be re-ordered by the optimizer based on cost.
Does the order of columns in an sql statement affect the speed of the query?
[ "", "mysql", "sql", "sql-server", "oracle", "" ]
I need to transform some strings from this format: ``` "1020202020" ``` To ``` "1-0-2-0-2-0-2-0-2-0" ``` How can I do that in a simple way? Thanks
Every day I wake up and think to myself "What impossible thing will CTEs make possible today?" ``` ;with cte as ( select '1020202020' inputstring, convert(varchar(max),'') outputstring union all select substring(inputstring,2,len(inputstring)), outputstring + left(inputstri...
Your question is unclear on the exact rules are for the placement of the hyphens. So, there might be some clever method using `replace()`. For your example string: ``` select replace(replace(col, '02', '-0-2'), '20', '2-0') ```
Add a '-' in a varchar SQL
[ "", "sql", "t-sql", "" ]
When trying to delete a user when logged in as the administrative user, I get the following error in my heroku logs: ``` 2015-03-24T07:47:23.506661+00:00 app[web.1]: Started DELETE "/users/1" for 128.252.25.47 at 2015-03-24 07:47:23 +0000 2015-03-24T07:47:23.534256+00:00 app[web.1]: SQL (4.4ms) DELETE FROM "users" ...
Add cascading delete to yout User model: ``` class User < ActiveRecord::Base .... has_many :cars, :dependent => :delete_all end ```
To add an alternative for those who don't want to delete associated records (maybe you want to keep the cars records for later use). ``` class User < ActiveRecord::Base .... has_many :cars, dependent: :nullify end ``` The associated record foreign\_key will be set to nil. Can be useful for people like me landing...
Rails app Foreign key error: Administrative user not allowed to delete other users in
[ "", "sql", "ruby-on-rails", "ruby", "heroku", "" ]
I have two SQL Tables that have a key based off First\_Name, Last\_Name & Date\_Of\_Birth. I am trying to write a simple transact sql to find exceptions where Table1 Patient\_Key is not found in Table2 Table 1 contains 152758 records and will be a new dataset every month Table 2 contains 8388 records and will continue...
Checking for rows to exist across multiple keys works much better with a `WHERE NOT EXISTS` correlated subquery: ``` SELECT * FROM Table1 T1 WHERE NOT EXISTS ( SELECT 1 FROM Table2 T2 WHERE T2.FIRST_NAME = T1.FIRST_NAME AND T2.LAST_NAME = T1.LAST_NAME AND T2.DATE_OF_BIR...
I would recommend `left join` for this: ``` SELECT T1.* FROM TABLE1 T1 LEFT JOIN TABLE2 T2 ON t1.first_name = t2.first_name AND t1.last_name = t2.last_name AND t1.date_of_birth = t2.date_of_birth WHERE t2.first_name IS NULL; ``` The problem with your query are the concatenations. If y...
Transact SQL using EXCEPT vs INTERSECT
[ "", "sql", "sql-server-2008", "t-sql", "" ]
I have two tables, object and object\_data, with object referencing object\_data by foreign key (the relation is 1:1). For a set of objects, I need to null their object\_data references and delete the corresponding object\_data rows, like this: ``` DELETE FROM object_data WHERE id IN ( SELECT object_data_id FROM objec...
Yes use CTEs (Common Table Expression) ``` WITH tmp AS (SELECT object_data_id FROM object WHERE ...), upd AS (UPDATE object SET object_data_id = NULL WHERE ...) DELETE FROM object_data WHERE id IN (SELECT object_data_id FROM tmp); ``` The first CTE called tmp is executed first and remembers the data you need l...
Sonds like the perfect job for the `ON UPDATE SET NULL` modifier to your FK constraint. [Per documentation:](http://www.postgresql.org/docs/current/interactive/sql-createtable.html) > `SET NULL` > > Set the referencing column(s) to null. ``` ALTER TABLE object DROP CONSTRAINT <fk_name_here>; ALTER TABLE object ADD C...
PostgreSQL: deleting rows referenced from another table
[ "", "sql", "postgresql", "foreign-keys", "referential-integrity", "" ]
I have an article table which has id and date (month/year) columns, first of all I would like to count ids and group them by date, then I would like to see which id belongs to which date group in single query like that: ``` id date count ----------------- 1 01/2015 2 2 01/2015 2 3 02/2015 1 4 03/...
``` SELECT id, date, COUNT(*) OVER (PARTITION BY date) AS Count FROM article ``` [Sql fiddle](http://sqlfiddle.com/#!6/64fd9/2)
Can't quite do that in one query, but you could use a CTE to produce a single result set: ``` create table #tt (id int null, dt varchar(8)) insert #tt values (1,'01/2015'), (2,'01/2015'), (3,'02/2015'), (4,'03/2015'), (5,'03/2015'), (6,'03/2015'), (7,'03/2015') ;with cteCount(d, c) AS ( select dt, count(id) from ...
Select ID, Count(ID) and Group by Date
[ "", "sql", "sql-server", "date", "count", "group-by", "" ]
I'm attempting to return `0.0` if the following function does not return anything: ``` CREATE OR REPLACE FUNCTION get_height(firstn VARCHAR, lastn VARCHAR) RETURNS FLOAT AS $$ DECLARE height FLOAT = 0.0; BEGIN SELECT into height AVG(((p.h_feet * 12) + p.h_inches) * 2.54) FROM player p WHERE p.firstna...
Here is the script I used. As you can see I run PostgreSQL 9.4.1. I used HeidiSQL to launch the queries. Are you sure that you correctly updated your function? I just noted that you used a different function ('player\_height') in a comment instead of 'get\_height' in you original post. ``` select version(); -- Postgre...
### Explanation The root of the problem is the fuzzy definition of "not anything". > if the following function does not return anything **`NULL` is not *nothing***, it's just unknown what it is exactly. "Nothing" in terms of SQL would rather be **no row** - nothing returned at all. That typically happens when no qua...
How to return a value from a function if no value is found
[ "", "sql", "postgresql", "function", "null", "plpgsql", "" ]
I've checked a few questions about this already but they don't do quite what I want and involve multiple columns and conditions so I'm going to distill it down to its most basic form. ``` SERIAL DATE_TIME 1 01/01/2015 12:00:00 1 01/01/2015 15:00:00 2 01/01/2015 13:00:00 1 02/01/2015 12:00:00 2...
I'm not sure on the *any RDBMS* part, but in T-SQL, and probably many others, you could do this: ``` SELECT Serial, MAX(Date_Time) AS Date_Time FROM [Table] GROUP BY Serial, CAST(Date_Time AS DATE) ``` From what I can find, it *sounds* like `CAST` is an ANSI standard, so it should work with "everything," but I'm not ...
Will not work on ALL SQL versions. However will work on ones that support WINDOW functions: ``` CREATE TABLE #a ( serial INT, date_time DATETIME ); INSERT INTO #a VALUES (1, '01/01/2015 12:00:00'); INSERT INTO #a VALUES (1, '01/01/2015 15:00:00'); INSERT INTO #a VALUES (2, '01/01/2015 13:00:00'); INSE...
Selecting most recent date per ID for every day
[ "", "sql", "database", "" ]
I'm trying to do a group by and return a boolean for whether the group by contains a value in the group. I have two Tables Title Table and Items Table. The Title.ID is a foreign key to my Items Table. My Items Table has a multiple format codes and I need to Select A Boolean if a group contains a format code The Sql...
``` select t.ID, max(case when i.Formatcode = 'DOD' then 1 else 0) as hasDODItem from Title as t inner join Item as i on i.TitleID = t.ID group by t.ID ``` or you can do this with subquery and `exists`: ``` select t.ID, case when exists ( select * from Item as i ...
Use `case`: ``` Select t.ID, (case when i.Formatcode = 'DOD' then 1 else 0 end) as hasDODItem From Title t join Item i on i.TitleID = t.ID group by t.ID ``` EDIT: If you just want to know ids that have a particular item, then use `exists` rather than a `join`: ``` Select t.ID, (case when exi...
SQL Group by with return boolean for any
[ "", "sql", "sql-server", "group-by", "" ]
--- **EDIT 2:** What I want to ask is: If I understood right, an `EXISTS` statement does not *filter* any tuples from a relation. So for what purposes is it used, since it does not *filter* any tuples? **EDIT:** To elaborate more, in the first example, the following is present in the subquery: ``` cities_stores.stor...
The example you're referring to uses correlated sub-queries. <http://en.wikipedia.org/wiki/Correlated_subquery> Here's an excellent answer explaining the mechanics behind it. <https://stackoverflow.com/a/11592277/2707705>
Note this statement in the subquery `"WHERE cities_stores.store_type = stores.store_type"`. it is where the inner table checks against outer table. in the examples, cities\_stores is the inner table, stores is the outer table in the main query. > EDIT 2: What I want to ask is: If I understood right, an EXISTS statemen...
Usage of EXISTS in MySQL
[ "", "mysql", "sql", "" ]
I have a table with time periods like (no overlap in time periods): ``` start_date end_date ----------------------------- 12-aug-14 12-nov-14 12-jan-15 12-apr-15 12-jun-15 12-aug-15 ... 5 more ``` I'm trying to find the in between time periods - something like: ``` 12-nov-14 12...
`sort` your table, use `rownum` and then `join` them: ``` WITH CTE AS ( SELECT START_DATE, END_DATE, ROWNUM AS RN FROM ( SELECT START_DATE, END_DATE FROM TABLE_NAME ORDER BY 1,2) ) SELECT T1.END_DATE, T2.START_DATE FROM CTE T1 JOIN CTE T2 ON T2.RN=T1.RN+1 ```
Use `lead()`. That is what the function is designed for: ``` select l.*, lead(start_date) over (partition by place_no order by start_date) as next_start_date, (lead(start_date) over (partition by place_no order by start_date) as next_start_date - end_date) as gap from lease l where l1.place_no = 'P1'; ``...
SQL to find date intervals
[ "", "sql", "oracle", "" ]
This question is a part of an insert statement in which I am trying to select a value from another value that can be inserted into a column. For example in my table OnlineServers, I have columns: ``` ID, ServerID, OnlineSince ``` In my second table ImportServers, I have columns with the data (The lines after NewYork...
``` INSERT INTO OnlineServers SELECT CASE ImportServerName WHEN '' THEN 0 ELSE ID END AS ServerID, GetDate() FROM ImportedServers s LEFT JOIN ServerLookup l on s.ImportedServerName = l.ServerName; ``` This should do it. You `LEFT JOIN` so you get every record from ImportedServers and use `CASE` to get 0 wher...
Maybe something like this: ``` SELECT FIRST(column_name) FROM table_name; ``` Limiting the return to the first match, also, shoudl teh from not be inside the select brackets? ``` select FIRST(ID) from ServerLookup where ServerLookup.ServerName = ImportServers.ServerName or ServerLookup...
SQL Server select column while inserting
[ "", "sql", "sql-server", "" ]
I have the following table: ``` Game | Name | Result | Stage 1 A W F 1 B L 0 2 C L F 2 D W 0 3 E L 0 3 F W 0 ``` The output I am looking for: ``` Game | Name | Result | Stage 1 A W F 2 ...
To perform a job of this sort without a self-join or an equivalent, you would want to use SQL window functions, which MySQL does not support. The join you are using is not too bad, but this would be a little simpler: ``` SELECT players.Game AS Game, players.Name AS Name, 'W' AS Result, 'F' as Stage FROM MyTa...
With "The winners only from stage F" you only need: ``` SELECT * FROM MyTable WHERE stage="F" and result="W"; ``` Your own result example however also shows name "D" which is not a winner in stage F.
SQL Query - Combined rows with selective columns [MySQL]
[ "", "mysql", "sql", "" ]
![enter image description here](https://i.stack.imgur.com/akypR.png) I want to display data in family tree. I can easily get using below query. i faced problem in where condition on city. If i search city is *paris* then it will display only those data which are belong to *paris* but i want to display those data which...
You can move the filter on "Paris" into the CTE's initial anchor query (i.e. the search for family head will also be constrained by the city). This predicate must not however be repeated on the recursive query after the `UNION` in the CTE (since there is no requirement to constrain children). I've assumed a column `Cit...
actually variable table could be more better than cursor so I utilize that plz check this query It should help you out. ``` declare @allheadCount int, @allheadCounttree int , @contactId int declare @city varchar(50), @name varchar(50) set @allheadCounttree =0 DECLARE @familyTree TABLE ( familyId int IDENTITY(1,1)...
Display data in family tree view with where condition
[ "", "sql", "sql-server", "sql-server-2008", "" ]