Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have a customer table and a separate table that stores addresses for customers. They often have at least two joined records in the address table, if not more. When I want a mailing list, I want the billing address for the customer, which is marked by a 'type' column in the address table. Unfortunately, not every cust... | This will get you the billing address if it exists, otherwise the shipping address:
```
select ifnull(a1.address, a2.address) from customer c
left join address a1 on c.id = a1.custid and a1.type = 'billing'
left join address a2 on c.id = a2.custid and a2.type = 'shipping'
```
if you wanted to check for other types, y... | ```
select c.id, a.id
from customer c join address a on a.custid = c.id
where a.type = 'Billing'
union
select c.id, a.id
from customer c join address a on a.custid = c.id
where a.type <> 'Billing'
and c.id not in (select custid from address a where a.type = 'Billing')
```
This is one way to do it. | MySQL Join chose only 1 condition from a series of conditions | [
"",
"mysql",
"sql",
"where-clause",
""
] |
When I try to count months between 2 dates I get the wrong result.
```
SELECT ROUND(MONTHS_BETWEEN(TO_DATE('23/01/2015','dd/mm/yyyy'),
TO_DATE('26/10/2014','dd/mm/yyyy')))
FROM dual;
SELECT ROUND(MONTHS_BETWEEN(TO_DATE('25/05/2015','dd/mm/yyyy'),
TO_DATE('05/05/2015','dd/mm/yyyy')))
FROM dual;
```
... | finaly i get it:
```
SELECT TRUNC(ROUND(MONTHS_BETWEEN(TRUNC(TO_DATE('23/01/2015','dd/mm/yyyy'),'mm'),TRUNC(TO_DATE('15/01/2015','dd/mm/yyyy'),'mm')))) + 1 FROM dual ;
``` | Try this
```
select
trunc( months_between(TO_DATE('2015/01/23','yyyy/mm/dd'),
TO_DATE('2014/10/26','yyyy/mm/dd')) ) mths
FROM dual;
``` | How to count months between two date? | [
"",
"sql",
"oracle",
"date",
""
] |
For example, I have such sql table of messages:
```
Id from_user_id to_user_id message
1 1 2 Hello
2 1 2 How are you?
3 1 3 Where are you?
```
And query SELECT DISTINCT to\_user\_id FROM messages; it returns
```
to_user_id
2
3... | You're going to want to do a self join:
```
SELECT m.*
FROM messages m
LEFT JOIN messages _m ON m.to_user_id = _m.to_user_id
AND _m.id > m.id
WHERE _m.id IS NULL
``` | Postgres offers `distinct on`, which is generally the best way to approach this type of problem:
```
select distinct on (to_user_id) m.*
from messages m
where m.from_user_id = 1
order by to_user_id, id desc;
``` | Sql query distinct + other columns | [
"",
"sql",
"postgresql",
"distinct",
""
] |
I want to write a query that counts every object in the database. I'm aware that you can query for statistics, but I want to know how to write this general type of query in case I need to do it again.
I have the results of this query, which gives every table name in the DB:
```
SELECT table_name
FROM information_sche... | Use plpgsql `EXECUTE` command.
You have two options. The first is anonymous code block with temporary table to save results:
```
CREATE TEMP TABLE IF NOT EXISTS results(table_name text, row_count bigint);
TRUNCATE results;
DO $$
DECLARE
tname text;
BEGIN
FOR tname IN
SELECT table_name
FROM inf... | You can use analytic functions to get the total count in each row.
```
SELECT
nspname AS schemaname,
relname AS TABLE_NAME,
reltuples AS ROW_COUNT,
SUM (reltuples) OVER () AS total_rows_count
FROM
pg_class C
... | Perform the sum of many count queries, from the result of an initial query | [
"",
"sql",
"postgresql",
""
] |
Example:
Lets say I have table `customerphonedetails` ( `customer_no` , `phone_no` ).
```
data is like this :
customer_no =2 Phone_no=11
customer_no =2 Phone_no=12
customer_no =2 Phone_no=13
customer_no =1 Phone_no=11
customer_no =1 Phone_no=12
customer_no =1 Phone_no=13
customer_no =3 Phone_no=22
```
Now I want to w... | You can check that all three `Phone_no` provided in the `where` are present for each `customer_no` using `having` clause:
```
select customer_no
from customerphonedetails
where Phone_no in (11, 12, 13)
group by customer_no
having count(distinct Phone_no) = 3
``` | ```
select DISTINCT customer_no
from table
where phone_no in(11,12,13)
```
It should be remove duplicate record. | Find all the customer having phone multiple number in a table | [
"",
"sql",
"oracle",
""
] |
This is my query
```
select U_YBID, T1.onhand
from oitw T1
inner join oitm T2 on T1.ItemCode=T2.ItemCode
where T1.WhsCode='01' and U_YBID is not null and u_YBId like '%/%'
```
It gives output like this:
```
302/02 41.000000
302/01 23.000000
X82/02 20.000000
355/01 2.000000
355/02 4.000000
355/03 5.000000
```
... | You can use `left`:
```
select left(U_YBID, 3)
, sum(T1.onhand)
from oitw T1
inner join oitm T2 on T1.ItemCode = T2.ItemCode
where T1.WhsCode = '01' and u_YBId like '%/%
group by left(U_YBID, 3)
``` | If length of string in column `U_YBID` before `/` is not static to `3` then you can write a query as:
```
SELECT U_YBID,SUM (T1.onhand) AS T1.onhand
FROM
(
select PARSENAME(REPLACE(U_YBID, '/', '.'), 2) AS U_YBID , T1.onhand
from oitw T1
inner join oitm T2 on T1.ItemCode=T2.ItemCode
where T1.WhsCode='01' and U_YBID ... | Group by substring and sum | [
"",
"sql",
"sql-server",
""
] |
I would like to find amounts that end in 999. What I have so far is:
```
select *
from bkpf_bseg_0010
where right(cast(dmbtr as int),3) = 999
```
But when I run the query I get the following error message:
> Arithmetic overflow error for type int, value = 4302564925.000000
The column `dmbtr` is a float. Any other ... | You get a number overflow when casting big numbers to `int` which has only a limited range. `bigint` should be enough.
```
where cast(dmbtr as bigint) % 1000 = 999
```
And you can also use modulo to get the last 3 digits | ```
select * from bkpf_bseg_0010 where right(cast(dmbtr as bigint),3) = 999
``` | sql - find amounts that end in 999 | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
```
LedgerId AccountId EntryType Debit Credit
2 2 D 50000.00 NULL
3 2 D 10000.00 NULL
4 2 C NULL 25000.00
6 2 C NULL 10000.00
7 ... | You can use [`coalesce`](https://msdn.microsoft.com/ru-ru/library/ms190349(v=sql.120).aspx):
```
coalesce(sum(Debit), 0) - coalesce(sum(Credit), 0)
``` | try this with use of isnull(value,0) it will take null values as 0
```
Select Accounts.ID [AccountID],Name,AccountType [AccountType],
SUM(isnull( Debit,0)) - SUM(isnull(Credit,0)) isnull([Balance],0) as
Balance FROM Accounts
join Dealers on Accounts.DealerId = Dealers.ID
join Ledger on Accounts.ID = ... | Arithmetic operation on null | [
"",
"sql",
"sql-server",
"conditional-statements",
""
] |
I want to pass a list of int's (comma separated) which is a field in my table
> ie. 1234, 2345, 3456, 4567
to my `IN` clause in `WHERE`. But the list is a string (`VARCHAR`), and I'm comparing to an int field. Is there a way for me to convert the list to list of ints?
`Enterprise_ID` is `INT`
Path is a field in t... | You can use SPLIT\_PART function in vertica to split the comma separated list into rows and insert them into a temp table. Use a query something like this to achieve your goal:
```
SELECT * FROM tbl_Enterprice WHERE Enterprice_ID IN ( Select Enterprice_ID from temp_table )
```
Split part function:
<https://my.vertica... | I would consider these two solutions to be anti-patterns and would recommend testing them for performance.
The first method uses functions that come in the flex table package.
```
SELECT values::INT as var1
FROM (
SELECT MapItems(v1) OVER () AS (keys, values)
FROM (
SELECT MapDelimitedExtractor( '1234... | Convert comma separated string to a list | [
"",
"sql",
"vertica",
""
] |
I am getting data from table for certain date range, but the query not getting data for today's date. Why does this happen?
```
select *
from mytable
where action_date >= to_date('01/07/2015', 'DD/MM/YYYY')
and action_date <= to_date('22/07/2015', 'DD/MM/YYYY');
```
Result is not showing `22/07/2015` data.
**Edit... | I have changed the query by this way, its working as expected.
```
SELECT *
FROM mytable
WHERE action_date >= to_date('01/07/2015', 'DD/MM/YYYY')
AND TRUNC(to_date(TO_CHAR(action_date, 'DD/MM/YYYY'), 'DD/MM/YYYY')) <= TRUNC(to_date('22/07/2015', 'DD/MM/YYYY'));
``` | Try to add the time part:
```
select *
from mytable
where action_date >= to_date('01/07/2015 00:00:00,000000000', 'DD/MM/YYYY HH24:MI:SS,FF9')
and action_date <= to_date('22/07/2015 23:59:00,999999999', 'DD/MM/YYYY HH24:MI:SS,FF9');
```
If you only give the date part, the time part is automatically added with the ... | Query not getting current date result | [
"",
"sql",
"oracle",
""
] |
I'm try to create table with clever sequence generator for using this insert-strucure:
```
insert into SOMEUSERS (SOMEUSERS_NAME, SOMEUSERS_PASSWORD)
values ('Artem', 'PracTimPatie');
```
instead of this:
```
insert into SOMEUSERS (SOMEUSERS_ID, SOMEUSERS_NAME, SOMEUSERS_PASSWORD)
values (2, 'Artem', 'PracTimPatie... | Oracle 12c introduces [Identity columns](http://docs.oracle.com/database/121/SQLRF/statements_7002.htm#CJAECCFH):
```
CREATE TABLE SOMEUSERS (
SOMEUSERS_ID NUMBER(10) GENERATED ALWAYS AS IDENTITY
CONSTRAINT SOMEUSERS__SOMEUSERS_ID__PK PRIMARY KEY,
SOMEUSERS_NAME VARCHAR2(50)
... | In postgres just use a serial like this:
```
CREATE TABLE SOMEUSERS (
SOMEUSERS_ID serial NOT NULL,
SOMEUSERS_NAME text,
SOMEUSERS_PASSWORD text
);
```
Your insert statement is then easy as:
```
INSERT INTO SOMEUSERS (SOMEUSERS_NAME, SOMEUSERS_PASSWORD)
values ('Artem', 'PracTimPatie');
```
If you wanna quer... | Sequence in Oracle/PostgreSQL with no ID in insert statement | [
"",
"sql",
"oracle",
"postgresql",
"sequence",
"ddl",
""
] |
I have a workflow application where the workflow is written to the DB as shown below when the status changes. There is no end time as it is a sequence of events. I want to create a query that will group by the WorkFlowID and total the amount of time spent in each. I am not sure how to even begin
My table and data look... | In SQL Server 2012+, you would just use `lead()`. There are several ways to approach this in SQL Server 2008. Here is one using `outer apply:
```
select t.WorkFlowId,
sum(datediff(second, EventTime, nextTime)) / 60.0 as NumMinutes
from (select t.*, t2.EventTime as nextTime
from table t outer apply
... | As an alternative:
```
;WITH t AS (
SELECT *,
ROW_NUMBER() OVER (ORDER BY EventTime) As rn
FROM
yourTable)
SELECT
t1.WorkFlowID,
SUM(DATEDIFF(SECOND, t1.EventTime, ISNULL(t2.EventTime, GETDATE()) / 60) As TotalTimeInMins
FROM t t1
LEFT JOIN t t2
ON t1.rn = t2.rn - 1
``` | Calculate total time spent by group and one datetime column | [
"",
"sql",
"sql-server-2008",
""
] |
For example, if I have string 'sunday', then I want to insert same value in 1000 rows using SQL only; without using loops. | If you don't want to use another table you can use:
```
INSERT INTO some_table (some_column)
SELECT 'Sunday'
FROM (
SELECT 1
FROM (SELECT 1 UNION SELECT 2) as d1
JOIN (SELECT 1 UNION SELECT 2) as d2
JOIN (SELECT 1 UNION SELECT 2) as d3
JOIN (SELECT 1 UNION SELECT 2... | If you already have a table that has more than a 1000 rows, you could do
```
insert into mytable (mycolumn) select "Sunday" from mytablewithmorethan1000 limit 1000
``` | SQL query to insert same value 1000 times without loop | [
"",
"mysql",
"sql",
"sql-server",
""
] |
While trying to restore SQL Server database or do any other actions which require exclusive database access it displays following error:
> Exclusive access could not be obtained because the database is in use. | try this..
```
USE master
GO
ALTER DATABASE AdventureWorksDW
SET SINGLE_USER
--This rolls back all uncommitted transactions in the db.
WITH ROLLBACK IMMEDIATE
GO
RESTORE DATABASE AdventureWorksDW
FROM ...
...
GO
``` | This will do what you are asking for, but will terminate all open connections and will rollback uncommitted changes
```
ALTER DATABASE <yourDB>
SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
``` | How to close all active database connections in one shot? | [
"",
"sql",
"sql-server",
"sql-server-2014",
""
] |
I have a query as below
```
Select sum(total) from sales
```
it will give the result as `123456789` because in back end data is stored with out decimal point.
I need to format it as `1234567.89`
i tried
```
select CONVERT(DECIMAL(10,2),SUM(total)) from sales
```
but it give the output as `123456789.00`
> how to m... | Divide by 100.0:
```
select CONVERT(DECIMAL(10,2), SUM(total) / 100.0)
from sales
``` | You should simply divide by 100. Something like this:
```
select sum(total) / 100 from sales
``` | how to place a decimal point just before last two digit of a number | [
"",
"sql",
"sql-server-2008",
""
] |
When attempting to run a ServiceStack service, I'm getting the following error:
When debugging, the code only runs once and does not cycle through twice, I've also put breakpoints on all other functions with datareaders and none of them are being hit first and therefore managed to narrow the issue down to this one fun... | I would put the connection, command, and datareader into using statements [MSDN](https://msdn.microsoft.com/en-us/library/htd05whh.aspx). It ensures the disposal of resources when the code is finished in the using block. So here is the code that I would use:
```
using con as new sqlconnection("connection string")
... | ```
dr.Close()
Conn.Close()
End While
```
These should be outside the while loop. You trying to read after you have closed the connection.
```
End While
dr.Close()
Conn.Close()
``` | VB Error: "There is a already a datareader associated with this command" | [
"",
"sql",
"vb.net",
"servicestack",
""
] |
On dropping a unique `constraint`, following error occurs,
> ORA-04098: trigger 'SYS.XDB\_PI\_TRIG' is invalid and failed re-validation
Having no permission to recompile this `trigger`.
What could be the problem here and is there any way we can solve this? | Found a solution to this,
The XDB Schema is invalid for the Database. So we are unable to drop any objects in this Database. So making the XDB schema valid, has solved this problem.
Thanks for your answers! | I wouldthink that you may be dropping a primary key check what constraint your dropping. if your dropping a pk and its being used as a foreign key then this would invalidate the trigger. | Unable to drop constraint | [
"",
"sql",
"oracle",
"constraints",
""
] |
I imported and am in the process of cleaning some data exported from an older Mainframe and have quite a few lines that start with an abnormal character (i.e. ASCII characters 194, 195, 226, etc). I can trim off most of the characters with a simple `remainder = trim(leading '%' from remainder)` (where '%' represents th... | Your query works correctly on my MySQL ( 5.5.44-0ubuntu0.14.04.1 ).
Possibly the reason it doesn't work for you is that, due to character set mismatch, what you *see* as a character 195 **is not a character 195 at all**; it might be for example a 0xCD hex, or an UTF8 sequence corresponding to 0xC38D hex, in which case... | So I finally found *a method*. Using
```
remainder = trim(leading Char(195) from convert(remainder using ASCII))
```
I was able to finally get rid of that pesky 'Í'. My only concern is that it really didn't trim anyway, it turned **ALL** of the ASCII characters over 127 that would normally fall into the 'Extended ASC... | Can't trim() Char(195) in MySQL | [
"",
"mysql",
"sql",
"ascii",
""
] |
I've got two tables:
1. `T1` is a table of data
* column `one` cannot have `null`
* column `two` and `three` can have `null`s
2. `T2` is a table of categorization rules
* it has the same columns as `T1` along with a `cat` column to represent the category
* the idea is that the first three columns have crit... | For future reference, I think I figured out a working answer: <http://sqlfiddle.com/#!9/595eb/1>.
Instead of using `*` (wildcard) in `T2` I use `null` and then in the query check if the value is `null`. This seems to have the desired/expected result.
```
WHERE
(T2.one is null or T1.one = T2.one) AND
(T2.two is nu... | From what I see, you have 2 problems: you cannot join tables on computed fields.
-> all rows in T1 where column two starts with 2
-> all rows in T1 where column two starts with 3 AND column 3 equals hi
cannot be done this way.
However, I suggest you use sql fiddle to show your example.
I have done it for you.
<htt... | find rows in Table1 that match criteria rows in Table2 | [
"",
"sql",
"ms-access",
"ms-access-2013",
""
] |
I want to insert a not null value. This is a example:
```
create table time(
a varchar2(9),
b varchar2(9),
c varchar2(9));
table create
insert into time (a,c) values ('qq','ee');
table altered
```
When I key this:
```
alter table time
modify b varchar2(9) not null;
```
This error come out:
```
alter table time
... | If you don't mention a column in an `insert`, then it gets the default value. By default, the default value is `NULL`. You can specify something else:
```
create table time (
a varchar2(9),
b varchar2(9) not null default 'NO VALUE',
c varchar2(9))
);
```
EDIT:
To get your `alter table` to work, update th... | It's not possible.
First you need to update the data in column b and then apply not null constraint.
```
Update time set b= 'NA' where b is null
go
ALTER TABLE time
ALTER COLUMN b varchar(9) NOT NULL
go
``` | Null values found | [
"",
"sql",
"oracle",
""
] |
I'm using Microsoft SQL 2012
I'm using OFFSET and FETCH NEXT for paging in a query. I do need the overall count though so, I'm using OVER() to get the overall count. The problem I'm having is that when I have a UNION in one of my queries, OVER() will return the total for that part of the UNION.
Example:
```
SELECT s... | Just need to combine the 2 queries then get your count and offset
```
SELECT *,
overall_count = COUNT(*) OVER()
FROM (
SELECT something
FROM tbl_something
WHERE something = @someparameter
UNION
SELECT something
FROM tbl_something
WHERE something = @someOtherParameter
) u
ORDER BY so... | Have you tried wrapping an additional Select Statement around your union? like below...
```
SELECT * FROM (
SELECT something
,overall_count = COUNT(*) OVER()
FROM tbl_something
WHERE something = @someparameter
UNION
SELECT something
,overall_count = COUNT(*) OVER()
FROM tbl_someth... | Using OVER() in a query that has a UNION | [
"",
"sql",
"sql-server",
""
] |
Does Oracle have a builtin function to create a date from its individual components (year, month and day) that just returns null on missing data?
I'm aware of `TO_DATE()` but I need to compose a string first and neither the `||` operator nor the `CONCAT()` function make it easy to handle missing data:
```
-- my_year ... | For your example, you can use `case`:
```
select (case when my_year is not null and my_year <> 0 and
my_year between -4713 and 9999
then TO_DATE(my_year || '-01-01', 'YYYY-MM-DD')
end)
```
Unfortunately, Oracle does not have a method of doing the conversion, if possible, and oth... | I've eventually composed a user-defined function to encapsulate the logic. It returns a date from its individual components or `NULL` if the date is not valid:
```
CREATE OR REPLACE FUNCTION TRY_TO_DATE (
V_YEAR IN NUMBER,
V_MONTH IN NUMBER,
V_DAY IN NUMBER
) RETURN DATE DETERMINISTIC IS
BEGIN
RETURN T... | Create date from year, month and day | [
"",
"sql",
"oracle",
"oracle10g",
"oracle-xe",
""
] |
I have an existing T-SQL query that returns a list of customers who need to be sent updates. As a part of the WHERE clause, the query checks to make sure the version conforms to a length of 6, and then appends additional characters.
Our latest version has a longer version, so I need to add a conditional statement to t... | You need parentheses around the select statements so that they get parsed as sub-queries. I noticed that the two code blocks are identical, but I guess they are meant to not be?
```
vr.cversion IN
(
CASE WHEN product.iproductid < 8 THEN
(
SELECT MAX
(
substring(cversion,1,... | You can't use `IF` inside a TSQL Statement. You can only use it on Stored Procedures.
Use `CASE` or [`IIF`](https://msdn.microsoft.com/en-us/library/hh213574%28v=sql.110%29.aspx) instead | Using a Conditional in a T-SQL WHERE Clause | [
"",
"sql",
"t-sql",
""
] |
I have the following which brings me back 3 sets of results correctly
```
SELECT TOP (1) rid,score, weight
FROM dbo.tblThree
WHERE (caseNo = '111111111')
ORDER BY rID DESC
SELECT TOP (1) rid,score, weight
FROM dbo.tblTwo
WHERE (caseNo = '111111111')
ORDER BY rID DESC
... | You can use the following to get your desired output:
```
WITH data AS (
SELECT rid,score, weight, ROW_NUMBER() OVER (ORDER BY rID DESC) AS rn
FROM dbo.tblThree
WHERE (caseNo = '111111111')
UNION ALL
SELECT rid,score, weight, ROW_NUMBER() OVER (ORDER BY rID DESC) AS... | Try the following:
```
select * from ( select top (1) rid, score, weight
from dbo.tblThree
where caseNo = '111111111'
order by rid desc) t1
union all
select * from ( select top (1) rid, score, weight
from dbo.tblTwo
where caseNo = '1111111... | Select Max Records on UNION ALL | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2008-r2",
"union-all",
""
] |
We have a column that stores a value in 24 hr time format. It is a string/text that users enter on to the interface. I need to convert it into sql time format so that I can do time difference calculations. How can I convert the string to time? Example:
```
StringColumn
1400
1600
```
needs to be
```
TimeColumn
140... | If your string value are always 4 characters (meaning 01-09 and not 1-9 for early hours) then this works:
```
convert(time, stuff(StringColumn,3,0,':'))
``` | You can do a conversion as in @jpw's answer, especially if you can use `DATEDIFF` on the results to get what you need.
Alternately you could perhaps do it as integer maths like:
```
SELECT (60*left('1900',2) + right('1900',2)) - (60*left('1400',2) + right('1400',2))
```
(I have used constants here, but you can repla... | 24hr time format string to sql time format | [
"",
"sql",
"sql-server-2012",
""
] |
I'm trying to select with reference to one column changing its time in MySQL, but I don't know how.
How will I do it?
Example:
Time original: 2015-07-20 22:10:52
Updated: 2015-07-20 23:59:59 | You can use [`timestamp`](https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_timestamp) to join the current `timestamp`'s date with the time you want to set:
```
UPDATE mytable
SET mytimestamp = TIMESTAMP(DATE(mytimestamp), '23:59:59')
``` | To update with no reference to previous column value, it's no different from other columns. To update with it, and based on certain part (second, month, year, whatever), you can use [DATE\_ADD](https://dev.mysql.com/doc/refman/5.6/en/date-and-time-functions.html#function_date-add) or [DATE\_SUB](https://dev.mysql.com/d... | Update time on timestamp column | [
"",
"mysql",
"sql",
"timestamp",
"sql-update",
""
] |
The following query excludes all accounts where `AMT` balance is 0.
Although I am trying to make an exception for accounts `L1_ORG_SEG_ID = 101, 102 and 105` even if it's value is equal to 0.
Can someone point me into the right direction? Thanks!
```
SELECT 'Table' colA
,O.L1_ORG_SEG_ID colb
,A.L1_ACCT_SEG_I... | Something like this should work
```
SELECT 'Table' colA,O.L1_ORG_SEG_ID colb,A.L1_ACCT_SEG_ID colc,
A.L2_ACCT_SEG_ID cold,A.L3_ACCT_SEG_ID cole, ' ' colf,A.ACCT_NAME colg,
'USD' colh,SUM(G.AMT) coli,' ' colj,' ' colk,' ' coll,' ' colm,'4'
coln,'2015' colo,
'4/24/15' colp,' ' colq,' ' colr,' ' cols,' ' colt,'... | You can OR the exclusion condition in your HAVING so it always includes the specified accounts like so:
`HAVING (SUM(G.AMT) <> 0 OR O.L1_ORG_SEG_ID IN ('101', '102', '105'))` | SQL query exception | [
"",
"sql",
""
] |
I'm sure I've done this type of operation a 1000 times before but for some reason this is not working for me. I'm doing a report to determine if a patient receive medication on a day. So regardless if they get 1 does or 5 doses in a day the value should be 1. Staff also do corrections on the system, that come in as neg... | I don't think you should be grouping by doses. Without seeing your data, I can only guess that, for example, there are two doses of quantity 2 on the 16th.
So try:
```
SELECT
DIM_DRUG_NAME_SHORT.Drug_Name_Short AS 'Med_Name_Short'
, SUM(Baseline.Doses) as 'DOT'
, Day(Baseline.Dispense_Date) as 'd_Date'
FR... | Remove Doses from your Group By list. You are using an aggregate function on it (SUM) which is correct, so it should not be in the GROUP BY. | SQL - Get Sum of Values with same Date | [
"",
"sql",
"sql-server",
""
] |
How can I populate the `NULL` value with the previous row per group?
Say something like,
```
+--------+---------+--------+
| Date | Product | Amount |
+ + + +
| 7/1/15 | Prod1 | 5 |
| 7/1/15 | Prod2 | 7 |
| 7/1/15 | Prod3 | 9 |
| 8/1/15 | Prod1 | NULL |
| 8/1/15 | Prod... | You can use `ISNULL`(or `COALESCE`) and a correlated subquery:
```
SELECT t.Date, t.Product,
Amount = ISNULL(t.Amount,
(SELECT TOP 1 Amount
FROM dbo.TableName t2
WHERE t2.Product = t.Product
AND t2.Amount IS NOT NULL
... | You need a query like this:
```
;WITH t AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY Product ORDER BY [Date]) rn
FROM yourTable)
, tt AS (
SELECT t1.[Date], t1.Product, t1.Amount, MAX(CASE WHEN t2.Amount IS NOT NULL THEN t2.rn END) AS LastSeq
FROM t t1
LEFT JOIN
t t2 ON t1.Product = t2.Produc... | How to populate NULL column with the previous column per group? | [
"",
"sql",
"sql-server",
"null",
""
] |
I'm trying to write a `Select` statement that increments a `column` value by 50, but the range can end up being 200,000 so I can't do it all in a case statement manually.
Something similar to this, but instead of manually writing the `increments`
```
Select count(order_id) as order_count,
case when revenue betwee... | Turn your `revenue` into the bucket value, then make string out of it:
```
SELECT count(order_id) AS order_count,
'$' || ((((revenue - 0.01)/50)::int + 1) * 50)::text AS revenue_bucket
FROM Orders
GROUP BY 2;
```
This obviously runs well past $200,000. | You can work with modulo to get this. Limit would be 101 in your example. All you have to do, is cast the result in a string and add the $ before it
```
Select count(order_id) as order_count,
case when revenue < limit then revenue - (revenue % 50) + 50
else ‘over $101’
end as revenue_bucket
from Or... | SQL Increment column value in select statement | [
"",
"sql",
"postgresql",
"amazon-redshift",
""
] |
I need to show the data from DB into a table of report file.
`my_table` looks like:
```
+----+-------+------+------+-------------------+-----------+-------+----+-------------------+
| id |entryID|userID|active| dateCreated |affiliateId|premium|free| endDate |
| 1 | 69856 | 1 | N |2014-03-22 13:... | SQLFiddle Demo: <http://sqlfiddle.com/#!9/20cc0/5>
The added column `entryID` does not matter for us.
I don't really understand what you want for `Total`, or the criteria for `affiliateID`. This query should get you started.
```
SELECT
DATE(dateCreated) as "Date",
count(dateCreated) as "No of Entries",
99845... | Your result is not so clear for the total is a count or sum and affiliate is sum or count also
but assuming total will be count and affiliate will be sum
here a query you might use to give you a result ( using ms-sql )
```
select DateCreated,count(EntryId) as Total,
sum(case when Premium='Y' then 1 else 0 end... | How to do one big select from table in MySQL? | [
"",
"mysql",
"sql",
"database",
""
] |
I am trying to count Same values in a column and want it to return a count there off.
```
| ITEM | COUNT |
+-------+-------+
| GREEN | 1 |
| GREEN | 2 |
| GREEN | 3 |
| RED | 1 |
| RED | 2 |
```
I tried
```
ROW_NUMBER() OVER (ORDER BY ITEM) AS Row
```
But that only counts each line 1 - 1000... | You'll want to include a `partition by` clause with the row\_number function. This makes the row\_number restart from 1 for each new type of item.
```
ROW_NUMBER() OVER (PARTITION BY ITEM ORDER BY ITEM) AS Row
```
this would give you a result like:
```
item Row
GREEN 1
GREEN 2
GREEN 3
RED 1
RED 2
``... | Try:
```
ROW_NUMBER() OVER (PARTITION BY ITEM ORDER BY ITEM) AS Row
```
or
```
ROW_NUMBER() OVER (PARTITION BY ITEM ORDER BY COUNT) AS Row
```
You can have count of each `ITEM` like this:
```
COUNT(*) OVER (PARTITION BY ITEM) As CountByItem
``` | Count same values in column SQL Server | [
"",
"sql",
"sql-server",
"sql-server-2008",
"count",
""
] |
Can some one please guide me what's wrong with this query? In SQL Server we just check the presence of the Object\_ID of a table to drop it and re-create it. I am new to Oracle and wrote this query:
```
declare Table_exists INTEGER;
BEGIN
Select count(*) into Table_exists from sys.all_tables where table_name='TABLEN... | The EXCEPTION clause lasts till the next END and not just the next statement. If you want to continue after catching the exception you need to add an additional BEGIN/END:
```
declare
Table_exists INTEGER;
BEGIN
BEGIN
Select count(*) into Table_exists from sys.all_tables where table_name='TABLENAME1... | When you are using `all_tables` filter the results for your
schema by adding `where owner = 'your_schema'`
or use `sys.user_tables`
> ALL\_TABLES describes the relational tables accessible to the current user
>
> USER\_TABLES describes the relational tables owned by the current user.
When use `execute_emmidiate` remo... | Oracle SQL - If Exists, Drop Table & Create | [
"",
"sql",
"oracle",
"plsql",
""
] |
In an SQL Server 2012 table I want to take all the rows from two columns and turn them into one row, still two columns, but each column being comma-separated.
For example
```
Customerid | FacilityId
-----------------------------
1 5678
2 9101
5 6543
```
... | you can use `FOR XML` like this [SQL Fiddle](http://sqlfiddle.com/#!3/c9478a/1)
**Query**
```
SELECT STUFF((
SELECT ',' + CONVERT(VARCHAR(10),Customerid)
FROM Customer
FOR XML PATH('')),1,1,'') as Customerid,
STUFF((
SELECT ',' + CONVERT(VARCHAR(10),FacilityId)
FROM Customer
FOR XML PATH('')),1,1,'') as FacilityId
``... | Here is a simple and fast way using [CONCAT](https://msdn.microsoft.com/query/dev10.query?appId=Dev10IDEF1&l=EN-US&k=k(CONCAT_TSQL);k(SQL11.SWB.TSQLRESULTS.F1);k(SQL11.SWB.TSQLQUERY.F1);k(MISCELLANEOUSFILESPROJECT);k(DevLang-TSQL)&rd=true), it will work from sqlserver 2012:
```
DECLARE @t table(Customerid int, Facilit... | Comma separate two separate columns | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2012",
""
] |
I am entering the following query below and getting duplicate values. I thought if I did a Left Outer Join that it wouldn't do that. I want `T0.` data for 2 of the 3 columns. The one column that I want `T1.` data is for the related customer name to the customer code. But it seems to want to populate the record twice.
... | Try using distinct keyword.
```
SELECT distinct
T0.CardCode
,T1.CardName
,T0.State
FROM CRD1 T0 LEFT OUTER JOIN OCRD T1 ON T0.CardCode=T1.CardCode
``` | Usually this means you have multiple matches on the join predicate in the related table. The left outer join ensures you keep all rows from the left table regardless of match or not, but doesn't prevent multiple matches if they happen to exist. Example:
```
with _left (id)
as (
select 3 union all
select 4 unio... | Why am I getting duplicate records for this query? I am performing a Left Outer Join | [
"",
"sql",
"t-sql",
"join",
"sapb1",
""
] |
I am using oracle SQL queries in an external Program (Pentaho Data Integration (PDI)).
I need to convert all columns to string values before I can proceed with using them.
What i am looking for is something that automatically applies the
```
select to_date(col1), to_date(col2),..., to_date(colN) from example_table;
`... | If you are looking for a solution in PDI, you need to create a job (.kjb) where in you take 2 transformations. **First .ktr** will rebuild the query and the **Second .ktr** will execute the new query.
**1. First Transformation:** Rebuild the query
[]... | > select TO\_CHAR(\*) from example\_table;
You should not use `*` in your production code, it is a bad coding practice. You should explicitly mention the column names which you want to fetch.
Also, **TO\_CHAR(\*)** makes no sense. How would you convert **date** to **string**? You must use proper **format model**.
In... | Convert all selected columns to_char | [
"",
"sql",
"oracle",
"pentaho",
"kettle",
"to-date",
""
] |
My string looks something like this:
```
\\\abcde\fghijl\akjfljadf\\
\\xyz\123
```
I want to select everything between the 1st set and next set of slashes
Desired result:
```
abcde
xyz
```
EDITED: To clarify, the special character is always slashes - but the leading characters are not constant, sometimes there are... | Use substring, like this (only works for the specified pattern of two slashes, characters, then another slash):
```
declare @str varchar(100) = '\\abcde\cc\xxx'
select substring(@str, 3, charindex('\', @str, 3) - 3)
```
Replace `@str` with the column you actually want to search, of course.
The `charindex` returns t... | You could do a `cross join` to find the second position of the backslash. And then, use `substring` function to get the string between 2nd and 3rd backslash of the text like this:
```
SELECT substring(string, 3, (P2.Pos - 2)) AS new_string
FROM strings
CROSS APPLY (
SELECT (charindex('\', replace(string, '\\', '\'... | SQL: how to select a substring between special characters | [
"",
"sql",
"string",
"sql-server-2014",
""
] |
I have an old database to refactor and have faced this table:
Member
```
id | Name | Role
1 | Tyler | 6
2 | Jane | 16
3 | Jack | 20
```
Role
```
id | role | Level
1 | Visitor | 1
2 | Member | 2
3 | Monthly Member | 4
```... | There, you asked for an example of the ugly approach (non-einstein approach)
For that one permutation
```
create table oldstuff
(
id int not null,
yuck int not null
);
create table newstuff_junction
(
userId int not null,
roleId int not null
);
insert oldstuff (id,yuck) values (1,20),(2,20);
insert... | You can do this using the bitwise "and" operator. I would expect following to get the matches:
```
select m.*, r.*
from member m join
role r
on (r.level & m.role) > 0;
```
However, your example is suggesting something more like:
```
from member m join
role r
on ((1 << r.level) & m.role) > 0;
```
... | Mysql - Conditional inserting after select query | [
"",
"mysql",
"sql",
""
] |
I have a column where I have values like:
```
Email_Password+oi8hu907b;New_eMail+Y;Email_Username+iugbhijhb8
```
Now I want to update New\_eMail attribute for all rows which has `Y` to `N` without affecting anything else.
Please advise. | i hate it but...
```
update table
set column = replace(column,'New_eMail+Y','New_eMail+N')
where column like '%New_eMail+Y%'
```
you don't need the WHERE clause but if you put a functional index on the table it may be quicker with it | My answer is a slight improvement over the answer from user davegreen100
Since they don't allow me to post it as a comment, I add it here.
```
update <<tablename>>
set <<columnname>> = replace(<<columnname>>,';New_eMail+Y;',';New_eMail+N;')
where <<columnname>> like '%;New_eMail+Y;%'
``` | Oracle Update table to set specific attribute value in semicolon separated values | [
"",
"sql",
"oracle",
""
] |
We have two tables `Country` and `CountryStates` with the following fields
```
Country
- CountryId
- CountryName
CountryStates
- StateId
- StateName
- CountryId
```
There are some Countries without any states added in the database.
Now we have to fetch only those countries where states are added. | You can use this query to retrieve only countries that have a state:
```
SELECT *
FROM Country AS C
WHERE EXISTS (SELECT TOP 1 1
FROM CountryStates CS
WHERE CS.CountryId = C.CountryId
)
``` | **Same Result can be obtained by using sample INNER JOIN..**
SELECT CountryID,CountryName
FROM Country C
INNER JOIN CountryStates S
ON C.CountryID = S.CountryID | Fetch corresponding States of Countries table | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I'm trying to rename a column name in order to aid mapping data from this database into another for a data push.
What I need to do is change the name of `StdType` to `IncomeType`, although no matter what I try it simply does not change the column name in the result.
This is my SQL query:
```
SELECT
'AA' + CAST(C... | You are Aliasing the table, not the column. Try this -
```
SELECT
'AA' + CAST(ClientID AS VARCHAR) AS AAID,
Description,
Convert(Money,Amount)/100 as Amount,
Note,
StdType AS IncomeType
FROM [Finstat_Income]
INNER JOIN #Assessments A
ON 'AA' + CAST(ClientID AS VARCHAR) = A.AAID
``` | Put your alias next to the column name.
```
SELECT
'AA' + CAST(ClientID AS VARCHAR) AS AAID,
Description,
Convert(Money,Amount)/100 AS Amount,
Note,
StdType AS IncomeType
FROM [Finstat_Income]
INNER JOIN #Assessments A ON 'AA' + CAST(ClientID AS VARCHAR) = A.AAID
``` | SQL Server column alias has no effect | [
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
I have a table and storing date value in it and I need to fetch that value and pass that as parameter to function. But whenever I try to execute my code it's throwing error like
```
ORA-00936: missing expression.
```
Following is my code sample:
```
SELECT refno,
Tatcalculate(to_timestamp(SELECT h_modified_d... | I would put the `to_timestamp()` around the column name, rather than around the select statement.
Also, you need to enclose the select statement in its own brackets. Thus:
```
SELECT refno, Tatcalculate((SELECT to_timestamp(h_modified_date,'DD/MM/YYYY HH24:MI:SS') FROM TPADETAILS WHERE refno='WOC0021946'))
FROM Table... | give column name
> SELECT refno, Tatcalculate(to\_timestamp(SELECT h\_modified\_date FROM
> TPADETAILS WHERE refno='WOC0021946','DD/MM/YYYY HH24:MI:SS')) as TAT
> FROM Table1; | How to pass Timestamp to Oracle Function? | [
"",
"sql",
"oracle",
"subquery",
"ora-00936",
""
] |
If u have a text ( mostly sql query ) and you want to put prefix on each line something like
sQ &= " And at the end of line "
Something like this.
```
SELECT
Name,Age
FROM
Users
Where
id<>0
```
I want
```
sQ &=" SELECT "
sQ &=" Name,Age "
sQ &=" FROM"
sQ &=" Users "
sQ &=... | I recommend Nimbletext. Add it your external tools for VS and SSMS.
A pattern of `sql &=" $0 "` gives the results you want. Tools, Options... turns trim off | In bash you can use awk:
--add prefix and suffix to each line a text file
```
awk '{ printf("sQ &=" %s "", $l);}' sample-text-file.txt
``` | SQL string format with quotes | [
"",
"sql",
"vb.net",
"text",
""
] |
I'm developing a website, where people will be able to play small games. At the end of each game the user will be given a score, which I wish to store in a MySQL database with a timestamp. This will allow me to present the data in a nice way further down the line.
I use a Facebook login system, so I currently have a t... | I will recommend some normalization here.
Your users table is fine. Create a games table to store information about games. Create a table that combines information about users and games and results. Something on the lines of:
```
create table users (
id int primary key,
name varchar(100),
uid int
);
create tab... | My suggestion would be the following:
So basically you have two tables one with the uid that you can use to search for the other info you need.
Plus you save stuff where needed
```
ID------Name------UID-------
1 Bob 123123
2 Marley 23134
ID-----UID------GameTime-----GameScore
1 123123 ... | SQL storing large amount of data for each user | [
"",
"mysql",
"sql",
"user-data",
""
] |
Maybe not the most descriptive subject line, but the question is, whilst this query below does exactly what I'm after, I would also like to return records when Note.Name = 'Travel Advisory' is NOT true.
HOWEVER, when there is no Note.Name that equals 'Travel Advisory' I would still like the select values to be returned... | It sounds like you want a `LEFT JOIN`:
```
SELECT Supplier.Name, Supplier.Changeoverday, Supplier.Code, Note.Notes
FROM Supplier
LEFT JOIN Note
ON Supplier.ID=Note.LINKID
AND Note.Name = 'Travel Advisory'
WHERE Supplier.TID = 315
AND
Supplier.SID = 2350
```
If there is no matching record in the `Note` table t... | Edit: I didn't notice you were selecting from 2 tables, I'd agree with the `OUTER JOIN` method that the other poster answered with. My way is a handy way to do it against 1 table (if you don't use table aliasing and an `OUTER JOIN`, that is...)
You can use a case to select the column and do what you want, just remove ... | SQL: Reducing select criteria when WHERE statement not true | [
"",
"sql",
"sql-server",
""
] |
I'd like to join IP routing table information to IP whois information. I'm using Amazon's RDS which means I can't use the Postgres [ip4r](https://github.com/RhodiumToad/ip4r) extension, and so I am instead using [int8range](http://www.postgresql.org/docs/9.2/static/rangetypes.html) types to represent the IP address ran... | I was thinking originally of a lateral join as in other suggested approaches (for example, the last query by Erwin Brandstetter, where he uses simple `int8` datatype and simple indexes), but didn't want to write it in the answer, because I thought that it is not really efficient. When you try to find all `netblock` ran... | I don't have really good answer for you, because I'm not familiar with gist indexes, but I'm kind of interested so I took a little look at your explain plan. A couple things stood out:
1) Your plan is using a nested loop join, even in the 250K example. It is seq scanning the larger table, and doing lookups on the smal... | Joining 2 large postgres tables using int8range not scaling well | [
"",
"sql",
"postgresql",
"amazon-web-services",
"amazon-rds",
""
] |
Supposed that I have the following table. How to display 'amount' only once based on column `ID` ?
```
ID Amount
1 10.00
1 10.00
1 10.00
2 10.00
2 10.00
2 10.00
```
Given the ff example the expected output should be like this :
```
ID Amount ... | Just change your partition to use ID:
```
SELECT ID
,CASE WHEN ROW_NUMBER() OVER(PARTITION BY ID ORDER BY ID) = 1
THEN Amount
ELSE 0.00
END [AMOUNT]
FROM TABLE
Order by ID, Amount Desc
``` | This should do it:
```
select id, iif(id=lag(id,1,0), 0, amount) from mytable order by id
```
basically, if the current id is the same as the id one row back, use 0. otherwise, use the amount column.
I am assuming, from the data you have provided, that "amount" stays the same for any single id. | Display column values only once | [
"",
"sql",
"sql-server",
""
] |
I have a query
```
Select age,qualification,sum(income) as total_income from employee
group by age,qualification;
```
I want to find rank on based total\_income for the group of age and qualification.
For example
```
19|Grad|5000|rank:1
19|Grad|4000|rank:2
19|Grad|3000|rank:3
26|Grad|6000|rank:1
26|Grad|5000|rank:... | [SQL Fiddle](http://sqlfiddle.com/#!4/41f539/4)
**Oracle 11g R2 Schema Setup**:
```
CREATE TABLE Employees ( Age, Qualification, Income ) AS
SELECT 19, 'Grad', 5000 FROM DUAL
UNION ALL SELECT 19, 'Grad', 4000 FROM DUAL
UNION ALL SELECT 19, 'Grad', 3000 FROM DUAL
UNION ALL SELECT 26, 'Grad', 6000 FROM DUAL
U... | ```
select age,qualification,total_income
row_number() over (partition by age,qualification order by income desc) as rank from
(
Select age,qualification,sum(income) as total_income from employee
group by age,qualification
) T1
``` | RANKing in group by in oracle | [
"",
"sql",
"oracle",
""
] |
I have database with statistics over a number of websites and I'm currently having an issue with a rather complex query that I have no idea how to do (or if it's even possible).
I have 2 tables: `websites` and `visits`. The former is a list of all websites and their properties, while the former is a list of each user'... | Here's something you can try:
```
SELECT main.*
FROM (
SELECT
w.web_id,
w.url,
w.last_scanned,
(SELECT COUNT(*)
FROM visits v
WHERE v.web_id = w.web_id
AND TIMESTAMPDIFF(DAY,v.added_on, NOW()) <=30
) AS visit_count,
TIMESTAMPDIFF(HOUR,w.last_scanned, NOW()) AS hrs_since_upd... | Just an improvment on @morgb query, using a table for visit count ranges
[SQL FIDDLE DEMO](http://sqlfiddle.com/#!9/eafd1/4)
```
create table visitCount (
`min` bigint(20),
`max` bigint(20),
`frequency` bigint(20)
);
SELECT main.*
FROM (
SELECT
w.web_id,
w.url,
w.last_scanned,
(SELECT COUNT... | Mysql - get results from complex criteria | [
"",
"mysql",
"sql",
""
] |
I have a sqlite table with timestamps in milliseconds as primary key each row should be 1 second or 1000 apart from one another. Sometimes my data recorder goes out and there is no data in the table for that time. How can I find the gaps using a SQL statement? A cursor based solution is possible I know.
```
table = PV... | This may work. Assuming the table name is "tstamps",
```
select a.ts
from tstamps a
where not exists
(select b.ts
from tstamps b
where b.ts = a.ts+1000)
and exists
(select c.ts
from tstamps c
where c.ts = a.ts+2000)
```
Another way
```
select a.ts
from tstamps a
where not exists
(select b.ts... | Something like this (Assuming PVT.TS is your Column name):
```
SELECT * FROM 'table' WHERE PVT.TS ISNULL;
```
or
```
SELECT * FROM 'table' WHERE PVT.TS IS NULL;
```
If your collector is actually entering a blank entry you might need
```
WHERE PVT.TS = ''
```
or
```
where ifnull(some_column, '') = ''
``` | How do I find gap in sqlite table? | [
"",
"sql",
"sqlite",
"gaps-and-islands",
""
] |
How to concatenate a column value with single quotes and a comma in sql?
```
select tpaa_id from dbo.Sheet
where tpaa_id is not null
```
At present query returns, value as ..
```
ABC123
ABC456
```
We have around 1000 records.
I expect to return as
```
'ABC123',
'ABC456',
``` | To get the values with comma , use below statement...
select field 1 || ',' from table name; | Use this construction
```
SELECT CONCAT(CHAR(39), MyString ,CHAR(39)) FROM Table
return '<MyString>'
``` | How to concatenate a column value with single quotes in sql? | [
"",
"sql",
"sql-server",
""
] |
I have the following table schema representing some players and the teams that they play for:
```
CREATE TABLE PLAYERS
(
NAME VARCHAR(64) NOT NULL,
BIRTHDAY TIMESTAMP NOT NULL,
TEAM VARCHAR(64) NOT NULL,
CAPTAIN BOOLEAN
);
```
My data looks like this
```
"PLAYER1","1998-02-13 00:00:00","TEAM_A",NULL
"PLAY... | I would start by getting the oldest player for each team without a captain like this:
```
SELECT team, MIN(birthday) AS minBirthday
FROM myTable
WHERE team NOT IN (SELECT DISTINCT team FROM myTable WHERE captain = 1)
GROUP BY team;
```
Once you have that, you can use it to update the captains using a JOIN:
```
UPDAT... | Try this
```
UPDATE players p1
SET captain = 1
WHERE birthday = (SELECT Min(birthday)
FROM players p2
WHERE p1.team = p2.team)
AND CAPTAIN <> 1
``` | Update Table based on minimal date within group | [
"",
"mysql",
"sql",
""
] |
I have a table that looks like this:
```
ID x1 x2 x3 x4
1 20 30 0 0
2 60 0 0 0
3 10 30 0 0
4 30 30 30 30
```
I want to be able to query this and return the ID with the number of columns that have more than 0 as their value in that row. So the result ... | Try this:
```
SELECT ID, z.cnt
FROM mytable
CROSS APPLY (SELECT COUNT(*) AS cnt
FROM (VALUES (x1), (x2), (x3), (x4)) x(y)
WHERE x.y > 0) z
```
This query makes use of a [Table Value Constructor](https://msdn.microsoft.com/en-us/library/dd776382.aspx) to create an in-line table whose *rows* ... | Try this:
```
Select
ID,
Case When x1 <> 0 Then 1 Else 0 End +
Case When x2 <> 0 Then 1 Else 0 End +
Case When x3 <> 0 Then 1 Else 0 End +
Case When x4 <> 0 Then 1 Else 0 End as Count
From MyTable
```
While this is easy to code, the more columns you have, the larger your select is going to be ... | Count how many columns have a specific value | [
"",
"sql",
"sql-server",
""
] |
How can I select no rows if any row in the result set meets a certain condition?
For instance:
```
Id|SomeColumn|Indicator
1 | test | Y
1 | test1 | Y
1 | test2 | X
2 | test1 | Y
2 | test2 | Y
3 | test1 | Y
```
Say I wanted to select all rows where Id = 1 unless there is a row with an indicator = X... | Something like this ?
```
SELECT *
FROM SOMETABLE
WHERE ID = 1
AND NOT EXISTS (SELECT 1 FROM SOMETABLE WHERE INDICATOR = 'X')
```
or, if you want the X to discriminate only on the same id:
```
SELECT *
FROM SOMETABLE t1
WHERE t1.ID = 1
AND NOT EXISTS (SELECT 1 FROM SOMETABLE t2 WHERE t1.ID = t1.ID AND INDICATOR... | There are not too many options to do this. Another option is to use `EXISTS`.
```
SELECT *
FROM SOMETABLE s1
WHERE ID = 1 AND INDICATOR = 'Y'
AND NOT EXISTS (SELECT TOP 1 ID FROM SOMETABLE s2 WHERE s1.ID = s2.ID AND INDICATOR = 'X')
``` | Select No Rows If Any Row Meets A Condition? | [
"",
"sql",
"t-sql",
""
] |
```
Row TimeStamp
____|________________________
1 | 2015-01-01 12:00:01.000
2 | 2015-01-01 12:00:02.000
3 | 2015-01-01 12:00:03.000
4 | 2015-01-01 12:00:04.000
5 | 2015-01-01 12:00:05.000
6 | 2015-01-01 12:00:06.000
7 | 2015-01-01 12:00:07.000
8 | 2015-01-01 12:00:08.000
9 | 2015-01-01 12:00:09.... | You could try this:
```
SELECT
t.TimeStamp,
(
SELECT MAX(t1.TimeStamp)
FROM MyTable t1
WHERE t1.Row < t.Row
) AS PrevTimeStamp
FROM MyTable t
WHERE t.Row >= 3 AND t.Row <= 6
```
This would give you side-by-side columns, one current and one previous. | ```
select b.id, max(a.timestamp)
from mytable a join mytable b
on a.id < b.id
where b.id between --desired values
group by b.id
```
Here is a fiddle with sample data: [fiddle](http://sqlfiddle.com/#!3/ebce1/27)
will this work for you? This will `join` on all the previous rows and then picks up the `max` timestamp w... | Select previous row for each entry in Table/List | [
"",
"sql",
"sql-server-2008-r2",
""
] |
I am using SQL Server 2012. I have table like this:
```
Val1 Val2 Val3 Val4
-------------------------------------------
1 25000.00 1 1900-01-01 00:00:00.000
2 25000.00 1 2012-04-02 00:00:00.000
1 25125.00 1 2013-01-01 00:00:00.000
1 25502.00 1 2014-01-01 00:00:00.000
2 25502.00 1 ... | Maybe this help you:
```
select t1.*
from table1 t1
join (
select max(Val1) as Val1, Val2, Val3
from table1
group by Val2, Val3
) t2 on t1.Val1=t2.Val1 and t1.Val2 = t2.Val2 and t1.Val3=t2.Val3
``` | this should work
```
SELECT
val1,
val2,
val3,
val4
FROM
(SELECT *,
ROW_NUMBER () OVER (PARTITION BY val2 ORDER BY val1 DESC) rn
FROM table1
) a
WHERE
rn = 1
``` | Group record by one column | [
"",
"sql",
"t-sql",
"sql-server-2012",
""
] |
I have query .
```
SELECT VendorID,VendorName,VendorType,FirstName,LastName,
VendorCompany,Contact,Phone,AltContact,Email,OpeningBalance,OpeningDate,VendorAccountNo ,Photo,VendorNotes FROM
Vendor inner JOIN VendorTypeTable ON Vendor.VendorTypeID=VendorTypeTable.VendorTypeID
```
Now on the other side , i want to... | While @Fireblade is absolutely correct, sometimes a UNION is the right answer if you have two queries returning the same fields. This allows you to tweak the performance of each independently of the other.
```
SELECT VendorID,VendorName,VendorType,FirstName,LastName,
VendorCompany,Contact,Phone,AltContact,Email,
Op... | Something like this
```
SELECT vendorid,
vendorname,
vendortype,
firstname,
lastname,
vendorcompany,
contact,
phone,
altcontact,
email,
openingbalance,
openingdate,
vendoraccountno,
photo,
vendornotes
FROM ... | OR Operator in inner join | [
"",
"sql",
"subquery",
"inner-join",
""
] |
I have variable in Oracle procedure declared like this:
```
myMsg VARCHAR2(256 BYTE)
```
How can I port it to mysql? Because this when I try to declare it in MySQL procedure:
```
DECLARE myMsg VARCHAR(256 BYTE);
```
MySQL throws me syntax error.
---
How can I port that Oracle variable definition to MySQL?
---
... | In MySql, varchar colums get declared like this
```
colname VARCHAR(256),
another VARCHAR(20) NOT NULL,
```
etcetera. The Oracle syntax is different.
In stored code in MySql, inside function or procedure scope, variables get declared like this:
```
DECLARE myMsg VARCHAR(256);
```
If you're not aware of t... | The maximum size of `varchar` in `mysql` is `255` before `mysql 5.0.3`
From `MySql` Doc:
> A variable-length string. M represents the maximum column length in
> characters. In MySQL 5.0, the range of M is 0 to 255 before MySQL
> 5.0.3, and 0 to 65,535 in MySQL 5.0.3 and later
In `MySQL 5.0.3 and later`, a `CHAR` len... | Migrating from Oracle to MySQL. VARCHAR2 length defined using bytes. How to port? | [
"",
"mysql",
"sql",
"oracle",
"migration",
""
] |
I have two tables, TABLE A has columns *token* (primary key) and *downtime* (`INT`), TABLE B has columns *token*, *status* (`ENUM` with 3 states: `active`, `unstable`, `inactive`), *duration* (`INT`).
I want to sum *duration* from TABLE B, only for the states `unstable` and `inactive`. And after that, assign the resul... | In mysql you can use join and update something as
```
update tablea a
join(
select
token,sum(duration) as duration from tableb
where state != 'active'
group by token
)b
on b.token = a.token
set a.downtime = b.duration
``` | try this:
```
UPDATE A a
INNER JOIN (
SELECT SUM(duration) AS s
FROM B
WHERE state <> 'active'
GROUP BY token
) b ON a.token = b.token
SET a.downtime = b.s
``` | MySql UPDATE statement with SELECT summarizing data from table 2 | [
"",
"mysql",
"sql",
""
] |
I have some data as below:
```
DECLARE @MyTable AS TABLE
(productName varchar(13), test1 int,test2 int)
INSERT INTO @MyTable
(productName, test1,test2)
VALUES
('a', 1,1),
('a', 2,2),
('a', 3,3),
('b', 1,4),
('b', 2,5),
('b', 3,6),
('a', 1,7),
('a', 4,8),
('a', 5,9)
;
SELECT... | You can solve this by using a trick with row\_numbers, so that you assign 2 different row numbers, one for the whole data and one that is partitioned by productname. If you compare the difference between these numbers, you can figure out when product name has changed, and use that to determine the max values for each g... | Please check the following SQL Select statement
```
DECLARE @MyTable AS TABLE (productName varchar(13), test1 int,test2 int)
INSERT INTO @MyTable
(productName, test1,test2)
VALUES
('a', 1,1),
('a', 2,2),
('a', 3,3),
('b', 1,4),
('b', 2,5),
('b', 3,6),
('a', 1,7),
('a', 4,8),
... | Multiple SQL MAX when items are not in order | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have table called `Orders`. There are three columns: `CustomerID`, `ProductGroup`, `Size`.
How can I get `TOP` selling size by `ProductGroup` from this table?
I can do it 1 by 1 with
```
SELECT TOP 1 Count(customerid) as customers, ProductGroup, Size
FROM Orders
WHERE ProductGroup = xxx
GROUP BY ProductGroup, S... | Not sure, but it may help you.
```
Declare @temp table(CustomerID int, ProductGroup varchar(10), Size int)
insert into @temp
Select 1,'ABC',15 union all
Select 2,'ABC',10 union all
Select 3,'XYZ',12 union all
Select 4,'ABC',15 union all
Select 3,'XYZ',12 union all
Select 3,'XYZ',12 union all
Select 3,'XYZ',15 union a... | Please check following SELECT query with [SQL Count using Partition By clause](http://www.kodyaz.com/t-sql/sql-count-function-with-partition-by-clause.aspx)
```
;with cte as (
SELECT
Distinct ProductGroup, Size,
COUNT(*) OVER (Partition By ProductGroup, Size) cnt
FROM Customers
)
select
... | select top selling size by product group from table | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
""
] |
I am using the following SQL CASE:
```
SELECT
BomMast.BomStockCode
, BomMast.BomDescription
, CASE
WHEN StkItem.AveUCst <= 0 THEN 'ERROR'
WHEN StkItem.AveUCst > 0 THEN (StkItem.AveUCst * BomComp.ProductionQty)
END AS TotalCost
FROM BomComp
INNER JOIN BomMast
ON BomMast.BomID = BomComp.... | Yes, text can be used as the result a case statement, as can any datatype, but each case must return the same type, as the results column must have **one type** only.
Your `[TotalCost]` column has conflicting data types. `[StkItem.AveUCst]` is a **float** and the literal value of `'ERROR'` is a **varchar**. If you are... | Change your query to:
```
SELECT BomMast.BomStockCode
,BomMast.BomDescription
,CASE
WHEN StkItem.AveUCst <= 0
THEN 'ERROR'
WHEN StkItem.AveUCst > 0
THEN CAST((StkItem.AveUCst * BomComp.ProductionQty) AS NVARCHAR(MAX))
END AS TotalCost
FROM BomComp
INNER JOIN Bom... | Adding text string to CASE Statement | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I'm trying to sort by a certain character on a string, for example,
before:
```
+----+---------+
| id | name |
+----+---------+
| 1 | red |
| 2 | red-a |
| 3 | red-xy |
| 4 | blue |
| 5 | blue-a |
| 6 | blue-xy |
+----+---------+
```
after:
```
+----+---------+
| id | name |
+----+---------+
... | ```
SELECT
CASE
WHEN RIGHT(`name`,LENGTH(`name`)-INSTR(`name`,'-')) = `name` THEN ''
ELSE RIGHT(`name`,LENGTH(`name`)-INSTR(`name`,'-'))
END AS `suffix`,
`name`
FROM
`table1`
ORDER BY
`suffix`, `name`
```
If no suffix is found, it will put the record in the first row set.
Caveat: the first dash i... | This will do what you're looking for. Wouldn't like to promise great performance if you had a lot of rows though:
```
select id, name from
(
select id,
name,
if (substring_index(name,'-', -1) = name, '', substring_index(name,'-', -1)) as grouping
from Table1
order by grouping, name
) as subT... | MySQL - sort by certain last string character | [
"",
"mysql",
"sql",
"string",
"sorting",
""
] |
i want to create an SQL select statement that will JOIN a few tables and yeidl results. Essentially i have two tables that are independent of one another. One table contains users (which is assumed to have the most up to date and correct information) and i have a placed holder table called players. The placeholder tabl... | To begin with, `userPlayer.id` is never different from `players.userId` (either both are something, or both are null), so you can dispense with that expression.
Also, use `coalesce()` in preference to `case when x is null` for clarity and brevity:
```
SELECT
teams.*, players.number, players.position,
players... | You could create a view where you can comfortably select teams by their id. In this case it is possible to optimize, because if players.userId is null then all values of user are null (because of left join). So you could create a union, if you have a lot of null entries it could be beneficial:
```
SELECT
teams.*, p... | SQL Case column is null redefine selectors | [
"",
"sql",
"join",
"left-join",
""
] |
Can't believe I am stuck with this but how can I check that value I am returning is null in select statement
```
IF EXISTS(SELECT TU.Tagged FROM TopicUser TU
WHERE TU.TopicId = @TopicId and TU.UserId = @UserId)
BEGIN
--do stuff
END
```
The value of `TU.Tagged` is `NULL` but yet it does go into the cond... | It looks like you need something like:
```
IF EXISTS(SELECT TU.Tagged
FROM TopicUser TU
WHERE TU.TopicId = @TopicId
AND TU.UserId = @UserId
AND TU.Tagged IS NOT NULL)
BEGIN
--do stuff
END
```
Otherwise, you're checking only if records meeting your criteria ex... | Solution 1 :
Use IsNULL() Function, When below query return null value IsNULL function replace null value with 0 and if condition treated as False.
```
IF EXISTS (SELECT IsNULL(TU.Tagged,0) FROM TopicUser TU
WHERE TU.TopicId = @TopicId and TU.UserId = @UserId)
BEGIN
END
```
Solution 2 :
Use (IS NULL OR I... | Check if a column's value is null in SQL Server | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have 2 following table structure
first is like this
```
szCustId szArClassId decCreditLimit szPaymentTermId
22101100071 AMORE 0.00 30 HARI_AMORE
22101100071 BELLISIMO 500.00 17 HARI_BELLISIMO
22101100071 CAPE 0.00 17 HARI_CAPEDISC
22101100071 F... | You can `join` two tables and use `sum` aggregate function with the `group by` clause to calculate total `decCreditLimit` for each `szCustId` and `bAllowToCredit`:
```
select t2.szCustId
, t2.bAllowToCredit
, sum(t1.decCreditLimit) as decCreditLimit
from table1 t1
join table2 t2 on t1.szCustId = t2.szCustId... | Try this query
```
select a.szCustId,a.bAllowToCredit,b.decCreditLimit from tablesecond a
join(
select szCustId,sum(decCreditLimit) as decCreditLimit from tablefirst)b
on a.szCustId=b.szCustId
``` | How to take sum of column with same id and different table in SQL? | [
"",
"sql",
"sql-server",
""
] |
We currently have the following columns:
```
CustomerID int
ArrivalDateTime datetime
CheckPoint varchar(20)
DepartureDateTime datetime
```
CheckPoint column records 24hr format time based on specific queries.
```
CustomerID ArrivalDateTime CheckPoint DepartureDateTime
1 2015-... | Try the following:
```
SELECT CustomerID
,CAST(CAST(ArrivalDateTime AS DATE) AS DATETIME) + CAST(CONCAT(LEFT([CheckPoint], 2), ':', RIGHT([CheckPoint], 2)) AS DATETIME) AS ArrivalDateTime
,DepartureDateTime
,DATEDIFF(MINUTE, CAST(CAST(ArrivalDateTime AS DATE) AS DATETIME) + CAST(CONCAT(LEFT([C... | Try this:
```
select
CustomerID
, DATEADD(day, DATEDIFF(day, 0, ArrivalDateTime), STUFF(CheckPoint_,3,0,':')) ArrivalDateTime
, DepartureDateTime
, DATEDIFF(mi, DATEADD(day, DATEDIFF(day, 0, ArrivalDateTime), STUFF([CheckPoint],3,0,':')), DepartureDateTime) as TimeInMinutes
from t;
```
If you don't w... | Concatenate + time difference | [
"",
"sql",
"sql-server",
"t-sql",
"datetime",
"sql-server-2012",
""
] |
I have a table that shows the status of each case with multiple jobs being performed simultaneously, I would like to have the results displayed so that it only shows the first and last instance. (Mainly I want to know when the job was first started and what's its last known status).
I've managed to get the results wit... | One way to do it is to use `ROW_NUMBER` function twice in ascending and descending order to get first and last rows of each group. See [SQL Fiddle](http://sqlfiddle.com/#!6/e9ff5/2/0)
```
WITH
CTE
AS
(
SELECT
ID
,Status
,dt
,Job
,Note
,ROW_NUMBER() OVER (PARTITION BY ID, Job ORDER BY dt ASC) ... | I don't think there's much wrong with your UNION idea. Is this what you have?
select id, job, status, max(date), job, note, 'max' as type from test1 group by job UNION
select id, job, status, min(date), job, note, 'min' as type from test1 group by job; | SQL Query: how to return only the first and last instance? | [
"",
"sql",
"sql-server",
"sql-server-2014",
""
] |
i have two columns - email id and customer id, where an email id can be associated with multiple customer ids. Now, I need to list only those email ids (along with their corresponding customer ids) which are having a count of more than 1 customer id. I tried using grouping sets, rollup and cube operators, however, am n... | I *think* this will get you what you want, if I am understanding you question correctly
```
select emailid, customerid from tablename where emailid in
(
select emailid from tablename group by emailid having count(emailid) > 1
)
``` | ```
SELECT emailid
FROM
( SELECT emailid, count(custid)
FROM table
Group by emailid
Having count(custid) > 1
)
``` | using group by operators in sql | [
"",
"sql",
"sql-server",
"group-by",
"cube",
"rollup",
""
] |
How can i get the first day(Monday) and last day(Sunday) for **EVERY** week in a month?
**Example: July 2015**
*Week 1*
First: 29-Jun
Last: 5-Jul
*Week 2*
First: 6-Jul
Last: 12-Jul
*Week 3*
First: 13-Jul
Last: 19-Jul
*Week 4*
First: 20-Jul
Last: 26-Jul
*Week 5*
First: 27-Jul
Last: 2-Aug | Try this:
```
SET DATEFIRST 1;
GO
declare @Month date = '150701';
declare @Index int = 1;
declare @StartWeek date;
declare @MonthWeek table ([Week] char(6), StartDate date, EndDate date)
set @StartWeek = DATEADD(dd, -(DATEPART(dw, @Month)-1), @Month)
insert into @MonthWeek([Week], StartDate, EndDate)
select 'Week '... | Here you go:
```
SELECT DATEADD(DAY, 2-DATEPART(WEEKDAY, CURRENT_TIMESTAMP), CURRENT_TIMESTAMP); -- first day of week
SELECT DATEADD(DAY, 2-DATEPART(WEEKDAY, CURRENT_TIMESTAMP) + 6, CURRENT_TIMESTAMP); -- last day of week
```
[`SQLFiddle Demo`](http://www.sqlfiddle.com/#!3/9eecb7db59d16c80417c72d1/1648) | How to get first day and last day for every week in a month? | [
"",
"sql",
"sql-server-2008",
""
] |
I need to generate a column for InvoiceID. and I want to keep the formate of this column like this
```
INV0000001,
INV0000002,
.
.
.
.
INV0000010,
INV0000011,
.
. and so on.
```
As you can see this column is increasing with last index.
How can i do this.
I'm using SQL Server 2012.
I have searched, but couldn't find... | Try using `computed column` [MSDN](https://msdn.microsoft.com/en-IN/library/ms188300.aspx)
```
CREATE TABLE Yourtablename
(
ID int IDENTITY (1,1) NOT NULL,
InvoiceID AS 'INV'+ right('000000'+cast(ID as varchar(20)),7) PERSISTED
);
```
[**SQLFIDDLE DEMO**](http://sqlfiddle.com/#!6/83552)
For more info on why ... | try, this one :- (completely dynamic)
```
Declare @NextInvoice Int = 0
Select @NextInvoice = Isnull(Max(Cast(Replace('INV0000011','INV','') As Bigint)),0) + 1
Select 'INV' + Left('0000000', (Len('0000000') -Len(@NextInvoice))) + Cast(@NextInvoice As Varchar(20))
``` | Create column which increases from last index | [
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
I installed SQL Server 2014 Express. It doesn't have SSIS, so I installed SQL Server 2014 evaluation. I still don't see SSIS. Am I installing it in a wrong way or does SSIS come only with purchased SQL Server 2014 Standard edition and above.
I need to load multiple flat files into a database so I can work on them toge... | SSIS IS NOT FREE !! We have to buy atleast the standard edition of Sql Server which is too costly if you are working for a small company.
Best way to load multiple files into a database without SSIS is to merge all files with same columns together in excel [Merging files](http://www.oaultimate.com/office/merge-multiple... | Express version comes without SSIS. Actually there is not free version of SSIS. You need either SQL Server Standard, Developer, or Enterprise edition to get access to BIDS. If you have Visual Studio then you can download SQL Server Data Tools and you will be able to create SSIS projects
if you have Visual Studio 2013,... | Does SQL Server 2014 evaluation copy provide SSIS | [
"",
"sql",
"sql-server",
"ssis",
""
] |
I've got the following dataset ordered by a specific column:
```
ratio
-----
1
1
1
0.8333
1
1.6667
3.3333
1
```
And I want to count the rows where ratio equals 1, but **only** until I reach a row where ratio **is not** 1.
For the above dataset my expected result would be *3* (the first three rows).
Of course I could... | You say that the data is "ordered by a specific column". If so, you can simply do:
```
select count(*)
from table t
where specificcolumn < (select min(t2.specificcolumn)
from table t2
where t2.ratio <> 1)
```
Depending on the ordering, the `<` may need to be `>`.
Note:... | If you have another primary key column in the table:
```
SELECT COUNT(`id`)
FROM `table`
WHERE `ratio` = 1
AND `id` < (SELECT `id` FROM `table` WHERE `ratio` != 1 ORDER BY `id` ASC LIMIT 0, 1)
``` | SQL Query to return count of rows until certain criteria is met | [
"",
"mysql",
"sql",
""
] |
I am stuck with escape characters which give different values.Please help me to solve this problem.Please help me why same query is giving different results.
**Query :**
```
SELECT * FROM APP_REALM_ENTRIES WHERE ID IN (SELECT ID FROM APP_ENTRIES where APP_EXT_CODE ='TTL1' AND VERSION_NUMBER='1.0.1');
```
***Result**... | As Justin suggested use bind variables. You'll achieve two things by doing that, you won't need to worry about getting the number of quotes correct, and more importantly, you'll close the door to SQL Injection vulnerabilities. You can do this by changing your open statement to the following:
```
open table_cursor for ... | You can avoid all the headaches associated to dynamic SQL and explicit cursor manipulation by using this very simplified implicit cursor for loop (Documentation: [Query Result Set Processing With Cursor FOR LOOP Statements](http://docs.oracle.com/database/121/LNPLS/static.htm#CIHCGJAD)):
```
for rec in (
SELECT *
... | Oracle Procedure Escape characters | [
"",
"sql",
"oracle",
"plsql",
""
] |
I have a table of orders,
```
Invoice Location Customer Code SalesPersonEmail
------------------------------------------------------
300001 001 CUS001 ?
300002 006 CUS002 ?
```
And a table of email groups,
```
Role Email
-----------------------------------... | A relatively simple way is to use `LEFT JOIN` and put the special number `001` for your location and special role names `Filtered_Group` and `No_Filter_Group` in the join condition.
In this [SQL Fiddle](http://sqlfiddle.com/#!3/3c6a6/2/0) you can comment/uncomment one line in the schema definition to see how it works ... | Try something like this.
**Note:** This is just a example am not sure about the tables and column of your schema. Replace with the respective tables and columns
```
SELECT CASE
WHEN location = '001' THEN (SELECT TOP 1 email
FROM email_table
... | SQL Joining tables with 'constants' | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
""
] |
I have a table which is a mapping table t1. It looks like the following:
```
+-------+---------+-------------+
| Reqid | FIELDID | LISTITEMID |
+-------+---------+-------------+
| 219 | 76 | 3548 |
| 219 | 86 | 2382 |
| 220 | 76 | 3548 |
| 220 | 86 | 3491 |
| ... | You almost had it. What you need to do is select all `Reqid` matching your conditions, and get all rows with that `Reqid`. This can be accomplished with a sub-query.
Done using two sub-queries:
```
SELECT *
FROM t1
WHERE Reqid in
(
SELECT t11.Reqid
FROM t1 as t11
WHERE
(t11.FIELDID='76' AND t... | you could just do an `EXIST` statement
```
SELECT DISTINCT
t.ReqID
FROM
t1 t
WHERE
((t.FIELDID = '76'
AND t.LISTITEMID = '3548')
OR (t.FIELDID = '77'
AND t.LISTITEMID = '3550'))
AND EXISTS ( SELECT
1
FROM
t1
W... | Get only rows where 2 conditions are fulfilled in Microsoft SQL | [
"",
"sql",
"sql-server-2008",
""
] |
I have a table wit customer with arrival date and departure date in a format '2014-25-11 00:00:00.000'. I am creating a query with to select those customer but I am having a error
> Conversion failed when converting date and/or time from character string.
But I want to find only with date `2014-25-11`
SQL query used... | > Conversion failed when converting date and/or time from character string.
Delete '%' from your values
Try this one:
```
select FirstName and LastName
from customer
where ArrivalDate > CAST('2014-25-11' AS DATE)
and DepartureDate < CAST('2014-29-11' AS DATE)
``` | if you only want to find the ones in the day 2014-25-11 you could use this
```
select FirstName and LastName from customer
where DATEPART(YEAR,ArrivalDate) = 2014
and DATEPART(month,ArrivalDate) = 25
and DATEPART(day,ArrivalDate)= 11
``` | How to find tables in database with date range SQL? | [
"",
"sql",
"sql-server",
""
] |
Say I have this table:
(column: `Row` is a count based on the column `ID`)
```
ID | Row | State |
1 | 1 | CA |
1 | 2 | AK |
2 | 1 | KY |
2 | 2 | GA |
2 | 3 | FL |
3 | 1 | WY |
3 | 2 | HI |
3 | 3 | NY |
3 | 4 | DC |
4 | 1 | RI |
```
I'd... | Use window version of `MAX`:
```
SELECT ID, Row, State, MAX(Row) OVER (PARTITION BY ID) AS MaxRow
FROM mytable
```
[**Demo here**](http://sqlfiddle.com/#!3/4b5c8/1) | You could join between a query on the table and an aggregate table:
```
SELECT t.*, max_row
FROM t
JOIN (SELECT id, MAX([row]) AS max_row
FROM t
GROUP BY id) agg ON t.id = agg.id
``` | How to get the max row count grouped by the ID in sql | [
"",
"sql",
"sql-server",
"select",
"filter",
"group-by",
""
] |
I have a MySQL database named shop and a table named orders with these columns:
```
`id(INT AUTO_INCREMENT PRIMARY KEY`)
`value(INT(30))`
`order_date(DATE)`
```
I want to create an SQL query to select only the orders placed Friday and Monday with a value larger then 100. | Use [DAYOFWEEK](https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_dayofweek)
```
select * from orders
where value > 100
and DAYOFWEEK(order_date) in (2,6)
``` | Try this
```
select * from table
where dayname(order_date) in ('friday','monday') and value>100
``` | Sql query day check | [
"",
"mysql",
"sql",
""
] |
I have the following function which returns a bit:
```
Declare @Ret bit
SET @Ret = 0
IF EXISTS ( Select * from tblExclusion where StatusID = 1 and AccountID = @AccountID )
Begin
SET @Ret = 1
End
Return @Ret
```
Now there can be multiple entries for the same AccountID in the table or none at all but only one entry wi... | An index may be necessary, reviewing a [sample execution plan](https://technet.microsoft.com/en-us/library/ms178071(v=sql.105).aspx) will reveal what index would improve.
If you were to modify your query to:
```
Declare @Ret bit
SET @Ret = 0
IF EXISTS ( Select 1 from tblExclusion where StatusID = 1 and AccountID = @A... | If it takes a long time to run, then I would suspect that there is no index on the column "AccountID". Adding an index on that column will probably significantly improve performance. However, without knowing how tblExclusion is defined, there is no way to be certain of this answer. Also, adding an index to StatusID wil... | SQL Server Function Efficiency If Exists | [
"",
"sql",
"performance",
"sql-server-2008",
"function",
"ssms",
""
] |
I have two tables one for saving user session values and second to save user session visit log. I am saving session value when user visit on first time, after that i am only saving visit of that session in visitlog table with date & time. Now i need to get those session record who don't visited in last two months.
**u... | Use NOT EXISTS
```
select t1.sessionid from usersessionlog as t1 where not exists
(select * from usersessionvisitlog as t2 where t1.sessionid =t2.sessionid
and visitdatetime>=date_add(current_date,interval -2 month))
``` | Using left join:
```
select sessionid from usersessionlog sl left join usersessionvisitlog vl
on sl.sessionid = vl.sessionid and visitdatetime > now() - interval 2 month
where vl.sessionid is null
```
Usually in MySQL `join` works faster than `in` clause. | How to get user records who don't visited in last two months using mysql | [
"",
"mysql",
"sql",
""
] |
I need to implement Categorization and Sub-Categorization on something which is a bit similar to golden pages.
Assume I have the following table:
# Category Table
```
CategoryId, Title
10, Home
20, Business
30, Hobbies
```
I have two options to code the sub-categorization.
# OPTION 1 - Subcategory Id is unique wit... | I would use this structure:
```
ParentId, CategoryId, Title
null, 1, Home
null, 2, Business
null, 3, Hobbies
1, 4, Gardening
1, 5, Kitchen
1, 6, ...
2, 7, Development
2, 8, Marketing
2, 9, ...
3, 10, Soccer
3, 11, Reading
3, 12, ...
```
In detail:
* only use one table, which **references itself**, so that you can ha... | Managing hierarchical data has some ways. One of the most important ones is `Nested Set Model`. [See here](http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/) for implementation. Even some content management systems like Joomla, use this structure.
**Update 2020:** As there are some considerations on... | database design - categories and sub-categories | [
"",
"sql",
"database",
""
] |
How do i add a calculated column to an Access table in SQL?
I know i can add a column with SQL like this:
```
ALTER TABLE Clients ADD COLUMN AccountDate TEXT(60)
```
Thanks,
Vítor | You cannot add a calculated column with SQL because calculated field requires an expression and that cannot be supplied through SQL. Technically, a calculated field is a base type - int, double, text etc. Above the base type is an expression that helps Access do the math/logic.
**You could use VBA to create a calculat... | I don't think MS Access supports computed columns. Instead, you can create a view:
```
create view v_clients as
select c.*, (col1 + col2) as col3
from clients;
``` | How to add a calculated column to Access via SQL | [
"",
"sql",
"ms-access",
"vba",
"ddl",
""
] |
Below is my sample data. Row 3 and 4 have the same st\_case (the primary key), but their dist\_min are different. I want to keep the row with the minimum dist\_min value. And please notice that there could be more than 2 duplicate rows associate with the same st\_case. Thank you so much for the help!
[ as mindm
from sample s
group by st_case
) ss
on ss.st_case = s.st_case and s.dist_min > ss.mindm;
``` | You can try this one:
```
DELETE t1 FROM table AS t1
LEFT JOIN table t2 ON t1.st_case = t2.st_case
WHERE t1.dist_min > t2.dist_min
``` | sql: keep only the minimum value if two rows have duplicate id | [
"",
"mysql",
"sql",
"database",
"duplicate-data",
""
] |
I am trying to exclude a list of Names in an
I have the table `Names`
```
id| Name | Surname
---------------------
1 | Michael | Kane
2 | Torben | Dane
3 | Dinge | Chain
4 | Django | Fain
5 | Juliett | Bravo
```
And i have the Table `Excludes`
```
id| Name
-----------
1 | Michael
2 | Torben
```
Now I have t... | If you are going to use a `join` (as opposed to `not in` or `not exists`), you want a `left join` and `where` clause:
```
SELECT n.*
From Names n LEFT JOIN
Excludes e
ON n.Name = e.Name
WHERE e.Name IS NULL;
```
A simple rule: *Never* use commas in the `FROM` clause. | Use a `left join` instead and filter out `null` values:
```
SELECT Names.*
FROM Names
LEFT JOIN Excludes ON Names.Name = Excludes.Name
WHERE Excludes.Name IS NULL
```
The `group by` clause seemed meaningless so I removed it.
Another option is to use the `not exists` predicate with a correlated subquery:
```
SELECT... | Why is a WHERE clause to exclude rows in SQLite not working as expected? | [
"",
"sql",
"sqlite",
""
] |
I have `KPI_LOG` table which contains `600000` record and the table is growing is everytime. I have `TIME_STAMP` coulmn in this table which specify when the record is created and i have to delete records which is older than 2 days from this table. I am using below query to perform deletion :
`delete from KPI_LOG where... | > delete from KPI\_LOG where SYSDATE - TIMESTAMP > 2;
If you are deleting more number of rows then you are keeping in the table, then you could do a **CTAS** i.e. `create table as select` and then drop the old able and rename the new table.
Make sure, you have an **index** on the `timestamp` column.
For example,
``... | Deleting a record requires a transaction log record. This is integral to consistency.
This also means that deleting records is far from cheap - in a case like this, when a single statement deletes hundreds of thousands of rows, each of those rows needs to be written to the transaction log first. There is no way around... | Deleting large records in oracle sql | [
"",
"sql",
"oracle",
"sql-delete",
"delete-row",
"large-data",
""
] |
How can I combine the following two triggers, one 'after insert' and the other 'after delete' into one trigger?
```
create trigger TechStaff_update_Studio
on TechStaff after insert
begin
update Studio
set employees = employees + 1
where studioID = Studio.studioID
end
create trigger TechStaff_update_Studio... | Like this, I guess:
```
create trigger TechStaff_update_Studio
on TechStaff after insert, delete
as
begin
update s set employees = employees
+ (select count(*) from inserted)
- (select count(*) from deleted)
from Studio s
end
```
Notice that you must actually count rows rather than assuming o... | Simply you could handle it in one trigger like this :
```
CREATE TRIGGER [dbo].[<TriggerName>]
ON [<SchemaName>].[<TabaleName>] FOR INSERT, DELETE
AS
........-- Your Code
```
And remember that inside the Trigger, you can use two tables `Deleted` and `Inserted` that they have the same as structure as your table and t... | Insert and delete in one trigger | [
"",
"sql",
"sql-server",
"t-sql",
"triggers",
""
] |
Full disclosure, I'm a noob at SQL
Given two sparce matrices A and B, defined as:
A(row\_number, column\_number, value) and B(row\_number, column\_number, value)
I don't understand how this query represents the multiplication of the two matrices:
```
SELECT A.row_number, B.column_number, SUM(A.value * B.value)
FROM... | ```
create table A
( column_number int,
row_number int,
value int
);
create table B
( column_number int,
row_number int,
value int
);
insert A (column_number,row_number,value) values (1,1,1),(1,2,2),(2,1,3),(2,2,4);
insert B (column_number,row_number,value) values (1,1,10),(1,2,20),(2,1,30),(2,2,40... | 1. Giving table name after `SELECT` will identify which table to refer to. Mainly useful in the case where both tables have same column names.
2. `GROUP BY` will aggregate the data and display one record per grouped-by value. That is, in your case, you'll end up with only one record per row-column combination. | How does this matrix multiply work in SQL? | [
"",
"mysql",
"sql",
"matrix",
"group-by",
"sum",
""
] |
Can I use any special character as alias name for my table column.
for e.g.: `select id as #,first_name,last_name from student;` | You would have to use [a quoted identifier](http://docs.oracle.com/cd/E11882_01/server.112/e41084/sql_elements008.htm#SQLRF00223):
```
select id as "#",first_name,last_name from student
```
You are allowed a # in an unquoted object name (which includes aliases), from object naming rule 7:
> Nonquoted identifiers can... | You could use **quoted-idetifier** i.e. **double-quotation marks** around the alias.
From the [docs](http://docs.oracle.com/cd/E11882_01/server.112/e41084/sql_elements008.htm#SQLRF51129),
> Database Object Naming Rules
>
> Every database object has a name. In a SQL statement, you represent
> the name of an object wit... | Sql: Using special characters as alias for table columns? | [
"",
"sql",
"oracle11g",
""
] |
I am having issues with a SQL query that ideally should return all the comments to a thread in a forum.
Right now i'm having the following query:
```
SELECT p.*, 'BBCode' AS Format,
FROM_UNIXTIME(TIME) AS DateInserted,
FROM_UNIXTIME(editTime) AS DateUpdated
FROM et_post p
LEFT JOIN et_conv... | Based on the provided SQLFiddle in the edited question, this works.
```
SELECT p.*, 'BBCode' AS Format,
FROM_UNIXTIME(TIME) AS DateInserted,
FROM_UNIXTIME(editTime) AS DateUpdated
FROM et_post p
INNER JOIN et_conversation c
ON c.conversationId = p.conversationId
and c.private = 0
join (
select conversationId,min(post... | The issue here appears very simple. Lets break down your statement:
```
SELECT p.*, 'BBCode' AS Format,
FROM_UNIXTIME(TIME) AS DateInserted,
FROM_UNIXTIME(editTime) AS DateUpdated
FROM et_post p
LEFT JOIN et_conversation c ON c.conversationId = p.conversationId
WHERE c.private = 0
AND ... | Query with NOT IN subquery returning 0 rows | [
"",
"mysql",
"sql",
"subquery",
""
] |
Hi I have data like-
```
ORDER_NUMBER REVISION_NUMBER
2-345 1
2-345 2
2-345 3
5-436 1
6-436 1
```
Now I need to pick only those order\_numbers which has only revision number 1 and that order\_number should not have any other revisi... | Another solution using not exists:
```
Select ordernumber from table a
WHERE NOT EXISTS (
SELECT 1
FROM table b
WHERE a.ordernumber = b.ordernumber and revisionnumber != 1)
``` | Since you say specifically you want to use `NOT EXISTS`...
```
SELECT * FROM Orders T WHERE T.REVISION_NUMBER = 1
AND NOT EXISTS ( SELECT * FROM Orders T2
WHERE T2.ORDER_NUMBER = T.ORDER_NUMBER
AND T2.REVISION_NUMBER <> 1)
```
[Here's an SQL Fiddle that demonstrates it in action](htt... | How to eliminate unwanted data using not exists in SQL | [
"",
"sql",
"oracle",
""
] |
I have a query that returns a dataset that returns results for two different years. There will be exactly two rows per location id (not necessarily in sequence):
```
+------+---------------------------------------+
| year | location_id | unique_1 | data
+------+---------------------------------------+
| 1990 | 1... | If you are guaranteed that there are exactly two rows for the same `location_id`, you can do it like this:
```
select
a.location_id
, b.data - a.data
from test a
join test b on a.location_id=b.location_id and a.data>b.data
```
This query ensures that two rows with the same location ids get joined together in su... | You can do this using conditional aggregation:
```
select t.location_id,
max(case when t.year = 2000 then data
when t.year = 1999 then - data
end) as diff
from table t
group by t.location_id;
``` | Query to subtract values from two different year columns? | [
"",
"mysql",
"sql",
""
] |
I have a table like below.
[](https://i.stack.imgur.com/2Il3L.png)
I need to get the data like below.
[](https://i.stack.imgur.com/P1PEb.png)
I have created two temp tables and ach... | At least I wouldn't use pivot for that, to my mind this is simpler to do with group by and row\_number:
```
select UserId, max(starttime) as starttime, max(endtime) as endtime
from (
select UserId,
case when StartOrEnd = 'S' then time end as starttime,
case when StartOrEnd = 'E' then time end as endtime,
... | Here is another method
```
declare @t table(userid int, StartOrEnd char(1), time datetime)
insert into @t
select 1,'S','2015-07-27 16:45' union all
select 1,'E','2015-07-27 16:46' union all
select 2,'S','2015-07-27 16:47' union all
select 2,'E','2015-07-27 16:48' union all
select 1,'S','2015-07-27 16:49' union all
se... | convert row to column using Pivot without any clause | [
"",
"sql",
"sql-server",
"sql-server-2008-r2",
"pivot",
""
] |
I have table `news` with this fields:
`idNews`
`idArea`
`title`
`text`
`date`
What I want to do is delete all duplicate rows with same `title` and `text` except one (the one with the earliest date) i already try some query without success.
I tried these queries, but they didn't work:
```
DELETE FROM news WHERE idNe... | Assuming `idNews` is a key then this should work:
```
delete from news
where idnews not in (
select idnews from (
select idnews from news
join (
select title, text, min(date) as min_date
from news
group by title, text
) x
on news.title = x.title
and news.text = x.text
... | One of the methods is
```
delete from table as t1 inner join
(
select title,text,min(date) as date from table group by title,text
) as t2 on t1.title=t2.title and t1.text=t2.text
where t1.date>t2.date;
``` | Delete duplicate rows with same text | [
"",
"mysql",
"sql",
"text",
"duplicates",
""
] |
I have the following table test:
Table: `Test`
```
create table test
(
number int,
name varchar(10)
);
```
Insertion:
```
insert into test values(111,'PersonA');
insert into test values(211,'PersonB');
insert into test values(311,'PersonC');
insert into test values(111,'PersonA');
insert into test values(212,'Perso... | Well I have done it using CTE.
For 1 to 2:
```
with cte
AS
(
SELECT COUNT(DISTINCT Number) as a,Name from test
group by name
)
select DISTINCT x.Number,z.Name
from cte z
inner join test x
ON z.name = x.name
WHERE z.a between 1 and 2;
```
Result:
```
number name
-------------
111 PersonA
211 Per... | ```
select * from test GROUP BY name
HAVING COUNT(name) > 1
``` | SQL Server 2008 R2: Select with condition | [
"",
"sql",
"sql-server",
"sql-server-2008-r2",
""
] |
```
declare @date Datetime ='',@query nvarchar(max);
set @date =getdate();
set @query='select * from [3].[Sync_Database_BTS].dbo.[Test] where [Test] >=cast(date,'+ @date +' ,103) ; '
exec sp_executesql @query
```
Can you please tell me what is my mistake . | You need to convert the `date` to `varchar` if you are using the `datetime` type in dynamic query
You cannot use `style` in `cast` function you need to use `Convert` instead. Also you need extra single quotes around `datetime` parameter.
```
DECLARE @date DATETIME ='',
@query NVARCHAR(max);
SET @date = Getd... | Just because you're using a dynamic query, that doesn't prevent you from using [parameters](https://msdn.microsoft.com/en-us/library/ms188001.aspx) and keeping everything nicely typed:
```
declare @date Datetime ='',@query nvarchar(max),@parms nvarchar(max);
set @date =getdate();
set @query=N'select * from [3].[Sync... | "Conversion failed when converting date and/or time from character string " on dynamic query | [
"",
"sql",
"sql-server",
""
] |
I have some queries like this
```
Alter Table Table1 ALTER COLUMN T1 varchar(MAX);
Alter Table Table1 ALTER COLUMN T2 varchar(MAX);
Alter Table Table1 ALTER COLUMN T3 varchar(MAX);
--Table2 does not have a column "R1" and is likely to give error
Alter Table Table2 ALTER COLUMN R1 varchar(MAX);
Alter Table Table2 ALT... | Use a try-catch block:
```
Alter Table Table1 ALTER COLUMN T1 varchar(MAX);
Alter Table Table1 ALTER COLUMN T2 varchar(MAX);
Alter Table Table1 ALTER COLUMN T3 varchar(MAX);
BEGIN TRY
Alter Table Table2 ALTER COLUMN R1 varchar(MAX);
END TRY
BEGIN CATCH
print 'error altering column R1 of Table2';
END CATCH;
... | You should use 'GO' between instructions in order to contine the execution no matter on the errors:
```
Alter Table Table1 ALTER COLUMN T1 varchar(MAX);
GO
Alter Table Table1 ALTER COLUMN T2 varchar(MAX);
GO
Alter Table Table1 ALTER COLUMN T3 varchar(MAX);
GO
Alter Table Table2 ALTER COLUMN R1 varchar(MAX);
GO
Alter T... | SQL - Continue running all SQL statements even after error | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have these tables:
* steps(stepId\_,stepName)
* stepOfProject(idProject\_,stepId\_,dateofStart)
* Project(IdProject\_,idResponsable)
I want to get the latest step in each project it is working with this query:
```
select stepName
from step
where step.step=(select max(idstep) from stepOfProject where idProject=1)... | Try this:
```
select s1.stepName, sp1.projectId
from steps s1
join stepOfProject sp1 on s1.stepId = sp1.stepId
left join stepOfProject sp2 on sp1.idProject = sp2.idProject
and sp2.stepId > sp1.stepId
where sp2.stepId is null
```
What the `left join` is doing here is checkin... | Maybe I totally don't get why you're after... and I think Nick is right -- why NOT use a group by, unless this is an academic exercise.
It would help to have some sample data an expected results, but short of that:
```
select
idProjectSummary.idProject, step.step, step.stepName
from
step
join (
select idPr... | How to resolve this OPERATION without using GROUP BY in "SQL" | [
"",
"mysql",
"sql",
""
] |
I am trying date control by month with this script
```
DECLARE @Date DATETIME = '2015-07-31';
DECLARE @MonthCount INT = 3;
DECLARE @controlDate DATETIME = '2015-04-28';
SELECT
MONTH(@controlDate),
MONTH(DATEADD(MONTH, -@MonthCount, @Date)),
IIF(MONTH(@controlDate) > MONTH(DATEADD(MONTH, -@MonthCount, @Dat... | This happens when you're not running on a correct version of SQL Server, or if the compatibility level of the database isn't set sufficiently.
To check compatibility level:
```
select compatibility_level
from sys.databases
where name = '<database name>'
```
To alter compatibility level:
```
alter database <databa... | It should work correctly. You can also use CASE expression
```
DECLARE @Date DATETIME = '2015-07-31';
DECLARE @MonthCount INT = 3;
DECLARE @controlDate DATETIME = '2015-04-28';
SELECT
MONTH(@controlDate),
MONTH(DATEADD(MONTH, -@MonthCount, @Date)),
case when MONTH(@controlDate) >
MONTH(DATEADD(MONTH,... | IIF 'Incorrect syntax near' error at SQL Server 2014 | [
"",
"sql",
"sql-server-2014",
"iif",
""
] |
I have this query here :
```
SELECT nsd.REGISTRATION_DATE,nsd.Subject_Name,nsd.Subject_Code,nsda.District_Name, nsda.Region_Name
FROM tbl1 AS nsd
LEFT JOIN
tbl2 AS nsda ON nsd.Subject_Code = nsda.Subject_Code
```
I need to group this query by `Subject_Name, District_Name and Region_Name.` i also want to ... | Since you're not using `REGISTRATION_DATE` in your `SELECT`, you can omit it.
```
SELECT
nsd.Subject_Name,
[Nr. Total] = ISNULL(COUNT(nsda.Subject_Code), 0),
nsda.Region_Name,
nsda.District_Name
FROM tbl1 nsd
LEFT JOIN tbl2 nsda
ON nsd.Subject_Code = nsda.Subject_Code
GROUP BY nsd.Subject_Name, nsd... | ```
SELECT nsd.Subject_Name AS [Subject], count(*) AS [Nr.Total], nsda.Region_Name AS [Region], nsda.District_Name AS [District]
FROM tbl1 AS nsd
LEFT JOIN
tbl2 AS nsda ON nsd.Subject_Code = nsda.Subject_Code
Group by nsd.Subject_Name, nsda.Region_Name, nsda.District_Name
```
If you need 'tbl1.REGISTR... | Add Group By in query and a counting variable | [
"",
"sql",
"sql-server",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.