Prompt
stringlengths 10
31k
| Chosen
stringlengths 3
29.4k
| Rejected
stringlengths 3
51.1k
| Title
stringlengths 9
150
| Tags
listlengths 3
7
|
|---|---|---|---|---|
In Java, a logical OR condition behaves such that if the first condition is `true` then it does not evaluate the second condition.
For example:
```
int a = 10;
if (a == 10 || a == 0) {
// Logic
}
```
Java does not evaluate the second test (`a == 0`) because the first condition (`a == 10`) is `true`.
If we have an Oracle SQL statement like this:
```
select * from student where city = :city and
(:age is null or age > :age)
```
How are `(age > :age or :age is null)` evaluated? If the parameter `:age` is `NULL`, then does it evaluate the second condition as well?
|
### PL/SQL
In PL/SQL, Oracle OR is another example of *short circuit* evaluation. Oracle [PL/SQL Language Fundamentals](http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/fundamentals.htm#LNPLS258) says (in part)
> ### Short-Circuit Evaluation
>
> When evaluating a logical expression, PL/SQL uses **short-circuit evaluation**. That is, PL/SQL stops evaluating the expression as soon as it can determine the result. Therefore, you can write expressions that might otherwise cause errors.
### SQL
However, in regular SQL, the OR *might* be evaluated in either order. As pointed out by [@JonHeller](https://stackoverflow.com/users/409172/jon-heller) in his comment *the expressions in this question are safe, more caution would be required if dealing with potential division by 0*.
|
The database cost optimizer will consider many factors in structuring the execution of a query. Probably the most important will be the existence of indexes on the columns in question. It will decide the order based on the selectivity of the test and could perform them in different order at different times. Since SQL is a declarative and not procedural language, you cannot generally control the way in which these conditions are evaluated.
There may be some "hints" you can provide to suggest a specific execution order, but you risk adversely affecting performance.
|
How does Oracle perform OR condition validation?
|
[
"",
"sql",
"oracle",
"logical-operators",
""
] |
Trying to insert values into a temporary table using SQL Server 2008, getting:
> Msg 116, Level 16, State 1, Procedure Test\_temp\_table, Line 274
> Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.
With this query:
```
VALUES(
(select
a.*, b.[formal name], c.*, d.*
from
selecthr20.employee.[career history] a,
selecthr20.Employee.[Current Appointments As At Evaluation Date] b,
Employee.[BSK Changes in Selected Period] c,
selecthr20.employee.[career history extra detail] d
where
a.[appointment number] = b.[appointment number]
and a.[career number] = c.[primary key number]
and a.[career number] = d.[career number]
and c.[primary key number] = d.[career number]
and c.[primary key name] = 'Career Number'
and b.[person number] in (select b.[person number]
from employee.[current pay as at evaluation date]
where substring([Payroll Name],1,6) = 'DOV020')))
```
|
If you are not going to create the temp table first, use select into.
```
IF OBJECT_ID('TEMPDB.DBO.#TEMP') IS NOT NULL
DROP TABLE #TEMP;
BEGIN
SELECT
a.*,
b.[formal name],
c.*,
d.*
INTO #TEMP
FROM selecthr20.employee.[career history] a,
INNER JOIN selecthr20.Employee.[Current Appointments As At Evaluation Date] b
ON a.[appointment number] = b.[appointment number]
INNER JOIN Employee.[BSK Changes in Selected Period] c
ON a.[career number] = c.[primary key number]
INNER JOIN selecthr20.employee.[career history extra detail] d
ON a.[career number] = d.[career number]
AND c.[primary key number] = d.[career number]
where c.[primary key name] = 'Career Number'
and b.[person number] in (select b.[person number] from employee.[current pay as at evaluation date] where substring([Payroll Name],1,6) = 'DOV020')
END
```
If you want to create the table first and then insert, here is a template to give you an idea of the structure.
```
CREATE TABLE #TEMP
(
<YOURCOLUMNS>
)
INSERT INTO #TEMP
(
<YOURCOLUMNS>
)
SELECT
<YOURCOLUMNS>
FROM selecthr20.employee.[career history] a,
INNER JOIN selecthr20.Employee.[Current Appointments As At Evaluation Date] b
ON a.[appointment number] = b.[appointment number]
INNER JOIN Employee.[BSK Changes in Selected Period] c
ON a.[career number] = c.[primary key number]
INNER JOIN selecthr20.employee.[career history extra detail] d
ON a.[career number] = d.[career number]
AND c.[primary key number] = d.[career number]
where c.[primary key name] = 'Career Number'
and b.[person number] in (select b.[person number] from employee.[current pay as at evaluation date] where substring([Payroll Name],1,6) = 'DOV020')
```
|
You're using the wrong syntax for an insert from a query result. For this type of insert, you don't need the `VALUES()` portion.
As a side-note, you should avoid using `SELECT *` (or, in this case, `a.*, c.*, d.*`) in your `INSERT SELECT` statement, as your temp table would have to be set up just right for that insert statement to work, and any changes to the target or source tables would cause that to break.
Your statement should look something like this:
```
Insert #YourTempTable
(List, Your, Columns, Here, ...)
Select a.*,
b.[formal name],
c.*,
d.*
From selecthr20.employee.[career history] a
Join selecthr20.Employee.[Current Appointments As At Evaluation Date] b On a.[appointment number] = b.[appointment number]
Join Employee.[BSK Changes in Selected Period] c On a.[career number] = c.[primary key number]
Join selecthr20.employee.[career history extra detail] d On a.[career number] = d.[career number]
And c.[primary key number] = d.[career number]
And c.[primary key name] = 'Career Number'
Where b.[person number] In
(
Select [person number]
From employee.[current pay as at evaluation date]
Where SubString([Payroll Name],1,6) = 'DOV020'
)
```
|
Issue inserting values with a subquery into temporary table SQL Server 2008
|
[
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
""
] |
I have two tables ,location and locationdata. I want to query data from both the tables using join and to store the result in a new table(locationCreatedNew) which is not already present in the MySQL.Can I do this in MySQL?
> SELECT location.id,locationdata.name INTO locationCreatedNew FROM
> location RIGHT JOIN locationdata ON
> location.id=locationdata.location\_location\_id;
|
Your sample code in OP is syntax in SQL Server, the counter part of that in MySQL is something like:
```
CREATE TABLE locationCreatedNew
SELECT * FROM location RIGHT JOIN locationdata
ON location.id=locationdata.location_location_id;
```
|
Use Query like below.
```
create table new_tbl as
select col1, col2, col3 from old_tbl t1, old_tbl t2
where condition;
```
|
Store records in a new table created by a query in mysql
|
[
"",
"mysql",
"sql",
"database",
""
] |
I have been trying to get a query that will take a date field from a table, and only show me the results where the date is over a year old (in respect to the current date).
I am using PHPMyAdmin for these queries. The time field's data type is 'date' (yyyy-mm-dd).
The code I have so far is
```
SELECT table1.time
FROM table1
WHERE table1.time > UNIX_TIMESTAMP(ADDDATE(NOW(),INTERVAL -52 WEEK))
```
But the query returns every row in the table, including ones that are less than a year old.
I have tried things like `WHERE SELECT table1.time < Date_add((yy, -1, GetDate())`
But that just returns `check the manual that corresponds to your MariaDB server version for the right syntax to use near 'LIMIT 0, 25' at line 3` errors, which I don't understand.
Any help would be greatly appreciated.
|
The easiest way would probably be to use [`date_sub`](https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_date-sub):
```
SELECT table1.time
FROM table1
WHERE DATE_SUB(CURRENT_DATE(), INTERVAL 1 YEAR) > table1.time
```
|
The easiest way is to check current year and compare data of table with current year data.
```
SELECT table1.time FROM table1 WHERE YEAR(table1.time) = YEAR(CURDATE())
```
|
SQL Query that returns dates that are over a year ago from the current date
|
[
"",
"mysql",
"sql",
""
] |
I am trying to list all the sales, which links with a customer ID, so I expect to see
```
sale ID customerID customerfirstname customerlastname
1 1 J Bloggs
2 2 G Green
3 1 J Bloggs
```
This is all I have no far and it's not quite right...
```
SELECT sale.sale_id
customer.customer_id ,
customer.customer_first_name ,
customer.customer_last_name ,
FROM mydb.customer , mydb.sale
WHERE sale.sale_id = customer_id
```
Here is my structure
```
CREATE TABLE `sale` (
`sale_id` int(11) NOT NULL,
`sale_items` int(3) NOT NULL,
`sale_paid` tinyint(1) DEFAULT NULL,
`customer_customer_id` int(11) NOT NULL,
PRIMARY KEY (`sale_id`,`customer_customer_id`),
KEY `fk_sale_customer1_idx` (`customer_customer_id`),
CONSTRAINT `fk_sale_customer1` FOREIGN KEY (`customer_customer_id`) REFERENCES `customer` (`customer_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `customer` (
`customer_id` int(11) NOT NULL,
`customer_first_name` varchar(45) DEFAULT NULL,
`customer_last_name` varchar(45) DEFAULT NULL,
`customer_address1` varchar(45) DEFAULT NULL,
`customer_address2` varchar(45) DEFAULT NULL,
`customer_address3` varchar(45) DEFAULT NULL,
`customer_post_code` varchar(45) DEFAULT NULL,
`customer_debit` varchar(45) DEFAULT NULL,
PRIMARY KEY (`customer_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
```
|
You are joining on the wrong field - both tables have a column referencing the customer id, which you should use. Additionally, you have a redundant comma after the last item in the select list and are missing one after the first item:
```
SELECT sale.sale_id,
customer.customer_id,
customer.customer_first_name,
customer.customer_last_name
FROM customer, sale
WHERE sale.customer_customer_id = customer.customer_id
```
Note, however, that using implicit joins (i.e., having more than one table in the `from` clause) is deprecated and discouraged, and you should probably use **explicit** joins instead:
```
SELECT sale.sale_id,
customer.customer_id,
customer.customer_first_name,
customer.customer_last_name
FROM customer
JOIN sale ON sale.customer_customer_id = customer.customer_id
```
|
you need to use `JOIN` to connect the tables.
from looking at your tables, it looks like `customer_customer_id` is the column on `sale` table that matches the customer id:
```
SELECT sale.sale_id
customer.customer_id ,
customer.customer_first_name ,
customer.customer_last_name
FROM customer INNER JOIN sale on
sale.customer_customer_id = customer.customer_id
```
|
Find all sales made by each customer
|
[
"",
"mysql",
"sql",
"select",
"mysql-workbench",
""
] |
I want to select all distinct values of `ColA`, which have at least one out of each element from a given set of values in `ColB`
Sample table:
```
ColA ColB
A 1
A 2
B 1
C 2
C 2
D NULL
E 1
E 2
E 2
E 3
```
Desired result: all ColA values which have at least once 1 and 2 as ColB values:
```
A (has 1 once, has 2 once)
E (has 1 once, has 2 twice)
```
I know I have to use `GROUP BY` but don't know the exact aggregate function, which one should I use?
```
SELECT ... FROM MyTable
GROUP BY ColA
HAVING at_least_values(ColB, (1, 2)) // something like this
```
What's a good solution?
|
You can count the values in the `having` clause using conditional logic:
```
having sum(case when colB = 1 then 1 else 0 end) >= 1 and
sum(case when colB = 2 then 1 else 0 end) >= 1
```
|
`intersect` is one way to do it.
```
SELECT ColA FROM MyTable where colB = 1
intersect
SELECT ColA FROM MyTable where colB = 2
```
|
GROUP BY ColA having various column values in ColB
|
[
"",
"sql",
"t-sql",
"sql-server-2014",
""
] |
I have two arrays in postgresql:
```
CREATE OR REPLACE FUNCTION func()
RETURNS void AS
$BODY$
declare
first integer[];
second integer[];
array_vb integer[];
array_vb2 integer[];
begin
code....
select array_agg(id) into first
from a
where id = any (array_vb);
select array_agg(id) into second
from a
where id = any (array_vb2);
end;
$BODY$
LANGUAGE plpgsql VOLATILE
```
I would like to add a `raise notice` that will print all items that are in first but not in second
for example:
```
first = [1,10,15,3,7]
second = [1,3,15,4]
```
it will print `10,7`
How do I do that?
|
You can use PostgreSQL [unsent](http://www.postgresql.org/docs/9.2/static/functions-array.html#ARRAY-FUNCTIONS-TABLE) function:
```
SELECT ARRAY(SELECT unnest(first) EXCEPT SELECT unnest(second))
```
Example:
```
SELECT ARRAY(SELECT unnest(ARRAY[1,10,15,3,7]) EXCEPT SELECT unnest(array[1,3,15,4]))
```
Gives:
```
array
--------
{10,7}
```
See SQLFiddle [here](http://sqlfiddle.com/#!15/9eecb7db59d16c80417c72d1e1f4fbf1/5028).
|
You can use [`intarray` extension](http://www.postgresql.org/docs/current/static/intarray.html):
```
create extension if not exists intarray;
select array[1,10,15,3,7] - array[1,3,15,4] as result;
result
--------
{7,10}
(1 row)
```
|
Given two arrays how to get items that are not in both?
|
[
"",
"sql",
"arrays",
"postgresql",
"relational-algebra",
""
] |
I have a Article table as shown below :
```
create table article(
artID int,
arttitle varchar(50)
)
```
I have inserted 4 records in as below:
```
insert into article values (1,'abcd');
insert into article values (2,'asfsdf asdf sdf ');
insert into article values (3,'asdfasdfa sd ');
insert into article values (4,'abcasdfsdd [Little]');
```
created a test stored procedure:
```
create procedure test
@aID int = null,
@atit varchar(50) = null
as
select * from article where artID = COALESCE(@aID,artID) and
arttitle like '%'+COALESCE(@atit,arttitle)+'%';
```
**Here is the problem :**
When I execute this `sp` with `aid = 1` it results with that record and similarly for `aid` 2 and 3.
But when I execute with `aid = 4` no results are coming becuase of those `square brackets [Little]`.
here is the stored procedure execution script :
```
exec test @aID = 4;
```
Please help me to achieve this. Thanks!
**Here is the sqlfiddle [link](http://sqlfiddle.com/#!3/8c9aa/14)**
|
If you don't want to use any of the function you can directly check `is null`
Check bellow SQL.
`select * from article
where (@aID is null or artID = @aID) and
(@atit is null or arttitle like '%'+ (@atit) +'%')`
|
This is because both `[]` are special characters and mean that one of the symbols, which is in brackets, must match. In order to fix it - you can escape these.
This is what you could do:
```
DECLARE @article TABLE
(
artID INT
, arttitle VARCHAR(50)
);
INSERT INTO @article
VALUES (1, 'abcd')
, (2, 'asfsdf asdf sdf ')
, (3, 'asdfasdfa sd ')
, (4, 'abcasdfsdd [Little]');
DECLARE @aID INT = 4
, @atit VARCHAR(50) = NULL
SELECT *
FROM @article
WHERE artID = COALESCE(@aID, artID)
AND arttitle LIKE '%' + COALESCE(@atit, REPLACE(REPLACE(arttitle, '[', '\['), ']', '\]')) + '%' ESCAPE '\';
```
I've replaced `[` with `\[` and `]` with `\]` and escaped `\`, so that square brackets are treated as casual characters.
|
special character in LIKE Operator with COALESCE is not working
|
[
"",
"sql",
"sql-server-2008",
"stored-procedures",
"sql-like",
"coalesce",
""
] |
I am trying to write a query from a table that contains 'Activities' for customers. Each activity is stored in a single line so if you call a contact and send an email after, it will be in two separate rows.
i.e.
```
Contact Employee Date Method
Jack John 12/7/15 11:50 Email
Jack John 12/7/15 11:45 Email
Jill John 12/4/15 10:19 Call
Rick Amber 12/8/15 9:40 Call
Dave Sarah 12/10/15 17:10 Email
Dave Sarah 12/10/15 17:15 Call
Dave Sarah 12/10/15 17:20 Email
```
I would like to return the most recent record for the call and if there isn't a call, then the most recent email.
So the output would return like this:
```
Contact Employee Date Method
Jack John 12/7/15 11:50 Email
Jill John 12/4/15 10:19 Call
Rick Amber 12/8/15 9:40 Call
Dave Sarah 12/10/15 17:15 Call
```
This is the current query I have written:
```
select FA.ContactID,
FA.Employee as [ContactedBy],
FA.CreatedDate as [ContactedDate],
case when max(FA.CreatedDate) and FA.PrincipalCall = 1 then 'Call'
when max(FA.CreatedDate) and FA.PrincipalCall = 0 and FA.InboundEmail = 1 then 'Call & Email'
end as [ContactMethod]
from WorkingData.dbo.FactActivities FA
where FA.CreatedDate >= CAST('12-04-2015' as date)
and (FA.PrincipalCall = 1 or FA.InboundEmail = 1)
```
Any ideas here?
|
The `row_number` window function can help here:
```
select t.contact, t.employee, t.date, t.method
from (select *,
row_number() over (partition by contact, employee
order by
case when method = 'Call' then 0 else 1 end,
date desc) as rn
from WorkingData.dbo.FactActivities) t
where t.rn = 1
```
Based on your desired results, I am assuming that you are looking for the latest `call/email` record for every `contact/employee` combination. If this is not exactly right, you just need to tweak the `partition by` clause in the query.
|
thanks to sstan; this is what I finished with:
```
select t.ContactID, t.Priority, t.ContactedBy, t.ContactedDate, t.ContactMethod
from (select FA.ContactID,
case when FA.PriorityLevel is null then 2 else FA.PriorityLevel end as [Priority],
FA.Employee as [ContactedBy],
FA.CreatedDate as [ContactedDate],
case when FA.PrincipalCall = 1 then 'Call'
when FA.InboundEmail = 1 then 'Email'
when FA.PrincipalCall = 1 and FA.InboundEmail = 1 then 'Call & Email'
end as [ContactMethod],
row_number() over (partition by FA.ContactID
order by case when FA.PrincipalCall = 1 then 0 else 1 end,
FA.CreatedDate desc) as rn
from WorkingData.dbo.FactActivities FA
where FA.CreatedDate >= CAST('12-04-2015' as date)
and (FA.PrincipalCall = 1 or FA.InboundEmail = 1)) t
where t.rn = 1
```
it doesn't matter who the employee was that made the contact, just that the contact was made with an individual on the list so i removed that from the partition
|
Return record with the max date based on certain criteria
|
[
"",
"sql",
"sql-server-2008",
"t-sql",
""
] |
I stuck on an SQL statement since 2 days now and I hope you can help me with that.
The result of my select is a list with 4 attributes A, B, C and D (below is an example list of 5 datasets):
```
1. A=1 B=100 C=200 D=300
2. A=2 B=200 C=100 D=300
3. A=3 B=300 C=200 D=100
4. A=3 B=100 C=100 D=200
5. A=3 B=300 C=100 D=200
```
The list shall be reduced, so that every attribute `A` is in the list only once.
In the example above the dataset 1. and 2. should be in the list, because `A=1` and `A=2` exists only once.
For `A=3` I have to build a query to identify the dataset, that will be in the final list. Some rules should apply:
1. Take the dataset with the highest value of `B`; if not distinct then
2. Take the dataset with the highest value of `C`; if not distinct then
3. Take the dataset with the highest value of `D`.
In the example above the dataset 3. should be taken.
The expected result is:
```
1.A=1 B=100 C=200 D=300
2.A=2 B=200 C=100 D=300
3.A=3 B=300 C=200 D=100
```
I hope you understand my problem. I've tried various versions of `SELECT`-statements with `HAVING` and `EXISTS` (or `NOT EXISTS`), but my SQL knowledge isn't enough.
|
Probably there is an easier way to solve this problem, but this one works:
```
CREATE TEMP TABLE TEST (
A INTEGER,
B INTEGER,
C INTEGER,
D INTEGER
);
insert into TEST values (1,1,1,1);
insert into TEST values (2,1,5,1);
insert into TEST values (2,2,1,1);
insert into TEST values (3,1,4,1);
insert into TEST values (3,2,1,4);
insert into TEST values (3,2,3,1);
insert into TEST values (3,3,1,5);
insert into TEST values (3,3,2,3);
insert into TEST values (3,3,2,7);
insert into TEST values (3,3,3,1);
insert into TEST values (3,3,3,2);
select distinct
t1.A,
t2.B as B,
t3.C as C,
t4.D as D
from TEST t1
join (select A ,MAX (B) as B from TEST group by A)t2 on t2.A=t1.A
join (select A, B, MAX(C) as C from TEST group by A,B)t3 on t3.A=t2.A and t3.B=t2.B
join (select A, B, C, MAX (D) as D from TEST group by A,B,C)t4 on t4.A=t3.A and t4.B=t3.B and t4.C=t3.C;
```
Result:
```
a b c d
1 1 1 1
2 2 1 1
3 3 3 2
```
Tested on IBM Informix Dynamic Server Version 11.10.FC3.
|
This type of prioritization query is most easily done with `row_number()`, but I don't think Informix supports that.
So, one method is to enumerate the rows using a correlated subquery:
```
select t.*
from (select t.*,
(select count(*)
from t t2
where (t2.b > t.b) or
(t2.b = t.b and t2.c > t.c) or
(t2.b = t.b and t2.c = t.c and t2.d > t.d)
) as NumGreater
from t
) t
where NumGreater = 0;
```
|
Reducing the list of results (SQL)
|
[
"",
"sql",
"informix",
""
] |
SQL help required.
Tables
* Person (id, name)
* Message (id, text)
* PersonMsgResponse (msgID, personID, delMethod, received(Y/N)
Structure of the PersonMsgResponse table
* MessageID (MsgId)
* PersonID (PerID)
* MessageDeliveredBy (DelMethod)
* Received (Y/N) (Received)
Example Rows within PersonMsgResponse table
[](https://i.stack.imgur.com/nMFNd.png)
I need to return a list of person names that did NOT receive the message.
How do I fashion the SQL to only return member names for those members that have not received the message via any of the methods?
For instance in the list of records above my query should only return member 1 since member 2 received the message by way of a phone call, whereas member 1 has not received the message by way of either method.
Thanks for all your help.
|
You can accomplish this with 2 inner queries like below. The trick is to include all Persons that have 'N' in received but do not have 'Y'. Message table is technically unnecessary for this example.
```
SELECT p.Name
FROM Person p
WHERE p.id IN (
SELECT personID
FROM PersonMsgResponse pmr
WHERE pmr.received = 'N' AND pmr.personID NOT IN (SELECT personID FROM PersonMsgResponse pmr WHERE pmr.received = 'Y')
)
```
This returns
```
Name
person 1
```
|
You can use `NOT EXISTS`:
```
SELECT Id, Name
FROM Person AS p
WHERE NOT EXISTS (SELECT 1
FROM PersonMsgResponse AS pmr
WHERE p.Id = pmr.personID AND p.Received = 'Y' AND
p.MessageID = 1)
AND EXISTS (SELECT 1
FROM PersonMsgResponse AS pmr
WHERE p.Id = pmr.personID AND p.MessageID = 1)
```
The above query will return a list of persons that did not receive a *specific* message in *any* of the available methods.
|
SQL Query to obtain result set based on inner join
|
[
"",
"mysql",
"sql",
"inner-join",
""
] |
I am working MS-Access 2007 DB .
I am trying to write the query for the Datetime, I want to get records between 14 December and 16 December so I write the bellow query.
```
SELECT * FROM Expense WHERE CreatedDate > #14-Dec-15# and CreatedDate < #16-Dec-15#
```
( I have to use the two dates for the query.)
But It returning the records having CreatedDate is 14 December...
Whats wrong with the query ?
[](https://i.stack.imgur.com/5cswl.png)
|
Thanks A Lot guys for your help...
I finally ended with the solution given by Darren Bartrup-Cook and Gustav ....
My previous query was....
```
SELECT * FROM Expense WHERE CreatedDate > #14-Dec-15# and CreatedDate < #16-Dec-15#
```
And the New working query is...
```
SELECT * FROM Expense WHERE CDATE(INT(CreatedDate)) > #14-Dec-15# and CDATE(INT(CreatedDate)) < #16-Dec-15#
```
|
As @vkp mentions in the comments, there is a `time` part to a date as well. If it is not defined it defaults to midnight (`00:00:00`). As `14-dec-2015 6:46:56` is after `14-dec-2015 00:00:00` it is included in the result set. You can use `>= 15-dec-15` to get around this, as it will also include records from 15-dec-2015. Same goes for the end date.
|
Giving the wrong records when used datetime parameter in MS Access Query
|
[
"",
"sql",
"ms-access",
""
] |
I've created the following stored procedure which should return all the location names that had an intersection with polygon group (without distinct... intersection with 3 polygons => 3 names)
```
CREATE OR REPLACE FUNCTION get_name_without_distinct_by_polygon_group(start_time TIMESTAMP,
end_time TIMESTAMP,
polygon_group_id INTEGER)
RETURNS TABLE(name_name_name_name VARCHAR(12)) AS $$
DECLARE
name VARCHAR(12);
poly_id INTEGER;
BEGIN
FOR poly_id IN (SELECT polygon_id
FROM polygon_group_members
WHERE group_id = poly_id)
LOOP
FOR name IN (SELECT DISTINCT name
FROM location, polygons
WHERE location.timestamp BETWEEN start_time AND end_time
AND poly_id = polygons.id
AND st_intersects(location.polygon, polygons.polygon))
LOOP
RETURN NEXT name;
END LOOP;
END LOOP;
RETURN;
END;
$$ LANGUAGE SQL;
```
When I tried to create this function I got the following error:
> [42601] ERROR: syntax error at or near "VARCHAR" Position: 356
Based on PostgreSQL [declaration documentation](http://www.postgresql.org/docs/9.1/static/plpgsql-declarations.html) it seems OK ...
What I've tried so far:
* I changed `name VARCHAR(12);` to `name location.mac%TYPE`
* I changed `name VARCHAR(12);` to `name RECORD`
* I changed the scope of the declaration then I got the same error on `poly_id INTEGER;`
* I changed the `LANGUAGE SQL` to `postgressql`
* I googled it and according to any example/problem I found this procedure should work.
|
Your posed answer still has a couple of problems. And you can very well use `RETURNS TABLE()`. Compare:
* [plpgsql error "RETURN NEXT cannot have a parameter in function with OUT parameters" in table-returning function](https://stackoverflow.com/questions/14039720/plpgsql-error-return-next-cannot-have-a-parameter-in-function-with-out-paramete/14039866#14039866):
```
CREATE OR REPLACE FUNCTION get_name_without_distinct_by_polygon_group(start_time timestamp,
end_time timestamp,
polygon_group_id int)
RETURNS TABLE(name_name_name_name VARCHAR(12)) AS
$func$
DECLARE
name VARCHAR(12); -- possible naming conflict!
poly_id int;
BEGIN
FOR poly_id IN -- no parentheses needed
SELECT polygon_id
FROM polygon_group_members
WHERE group_id = poly_id -- I suspect you really want polygon_group_id here
LOOP
FOR name_name_name_name IN -- assign directly
SELECT DISTINCT name -- l.name or p.name??
FROM polygons p
JOIN location l ON st_intersects(l.polygon, p.polygon)
WHERE p.id = poly_id
AND l.timestamp BETWEEN start_time AND end_time
LOOP
RETURN NEXT; -- already assigned
END LOOP;
END LOOP;
RETURN;
END
$func$ LANGUAGE plpgsql;
```
Be aware of possible naming conflicts. All declared variable and parameters (including fields in the `RETURNS TABLE()` clause are visible in SQL queries inside the body of a plpgsql or SQL function. A widespread convention would be to prepend variable names with `_` and table-qualify all columns in queries. See earlier answer from today:
* [Check for integer in string array](https://stackoverflow.com/questions/34277798/check-for-integer-in-string-array/34288654#34288654)
The whole function could probably be replaced with a single `SELECT` statement.
|
You don't need PL/pgSQL for this. The loops are unnecessary and will make everything very slow.
As far as I can tell this should do it:
```
CREATE OR REPLACE FUNCTION get_name_without_distinct_by_polygon_group(start_time TIMESTAMP,
end_time TIMESTAMP,
polygon_group_id INTEGER)
RETURNS TABLE(name_name_name_name VARCHAR(12))
AS
$$
SELECT DISTINCT name
FROM location, polygons
WHERE location.timestamp BETWEEN start_time AND end_time
AND poly_id IN (SELECT polygon_id FROM polygon_group_members WHERE group_id = polygon_group_id)
AND st_intersects(location.polygon, polygons.polygon));
$$
LANGUAGE SQL;
```
I also think that the condition `WHERE group_id = poly_id` is wrong as you are using the variable that should store the result in the `where` clause. I think you meant to use `WHERE group_id = polygon_group_id` (I changed that in the above code)
---
When using `language sql` you cannot use procedural code like `begin ... end` or declare variables.
The error `ERROR: syntax error at or near "VARCHAR" Position: 356` is caused by using `language sql` but using PL/pgSQL inside the function body. If you change `language sql` to `language plpgsql` in your definition, it should work (but again that solution having two nested loops is not very efficient).
|
'syntax error at or near "VARCHAR"' in DECLARE section when trying to create function
|
[
"",
"sql",
"postgresql",
"plpgsql",
"user-defined-functions",
"stored-functions",
""
] |
I am trying to retrieve data from an XML file. Below is how the XML doc looks and below that is my SQL code. It will run the code and show column headers - but will not populate with any data. What am I missing?
```
<profile xmlns="http://feed.elasticstats.com/schema/mma/v1/participants-profile.xsd" generated="2015-12-10T17:34:54Z">
<fighters>
<fighter id="01585452-852a-4b40-a6dc-fdd04279f02c" height="72" weight="170" reach="" stance="" first_name="Sai" nick_name="The Boss" last_name="Wang">
<record wins="6" losses="4" draws="1" no_contests="0" />
<born date="1988-01-16" country_code="UNK" country="Unknown" state="" city="" />
<out_of country_code="UNK" country="Unknown" state="" city="" />
</fighter>
<fighter id="0168dd6b-b3e1-4954-8b71-877a63772dec" height="" weight="0" reach="" stance="" first_name="Enrique" nick_name="Wasabi" last_name="Marin">
<record wins="8" losses="2" draws="0" no_contests="0" />
<born date="" country_code="UNK" country="Unknown" state="" city="" />
<out_of country_code="UNK" country="Unknown" state="" city="" />
</fighter>
```
---
```
DECLARE @x xml
SELECT @x = P
FROM OPENROWSET (BULK 'C:\Python27\outputMMA.xml', SINGLE_BLOB) AS FIGHTERS(P)
DECLARE @hdoc int
EXEC sp_xml_preparedocument @hdoc OUTPUT, @x
SELECT *
FROM OPENXML (@hdoc, '/fighters/fighter', 1) --1\ IS ATTRIBUTES AND 2 IS ELEMENTS
WITH (
id varchar(100),
height varchar(10),
last_name varchar(100)
) --THIS IS WHERE YOU SELECT FIELDS you want returned
EXEC sp_xml_removedocument @hdoc
```
|
Firstly repair the data (`:xs`, `</fighters>`, `</profile>`)
```
<profile xmlns:xs="http://feed.elasticstats.com/schema/mma/v1/participants-profile.xsd" generated="2015-12-10T17:34:54Z">
<fighters>
<fighter id="01585452-852a-4b40-a6dc-fdd04279f02c" height="72" weight="170" reach="" stance="" first_name="Sai" nick_name="The Boss" last_name="Wang">
<record wins="6" losses="4" draws="1" no_contests="0" />
<born date="1988-01-16" country_code="UNK" country="Unknown" state="" city="" />
<out_of country_code="UNK" country="Unknown" state="" city="" />
</fighter>
<fighter id="0168dd6b-b3e1-4954-8b71-877a63772dec" height="" weight="0" reach="" stance="" first_name="Enrique" nick_name="Wasabi" last_name="Marin">
<record wins="8" losses="2" draws="0" no_contests="0" />
<born date="" country_code="UNK" country="Unknown" state="" city="" />
<out_of country_code="UNK" country="Unknown" state="" city="" />
</fighter>
</fighters>
</profile>
```
Then the code
```
FROM OPENXML (@docHandle, 'profile/fighters/fighter', 1)
```
and we are done
```
01585452-852a-4b40-a6dc-fdd04279f02c 72 Wang
0168dd6b-b3e1-4954-8b71-877a63772dec Marin
```
|
`FROM OPENXML` is not the best approach any more. Try it like this:
Just copy this into an empty query window and execute:
```
DECLARE @xml XML=
'<profile xmlns="http://feed.elasticstats.com/schema/mma/v1/participants-profile.xsd" generated="2015-12-10T17:34:54Z">
<fighters>
<fighter id="01585452-852a-4b40-a6dc-fdd04279f02c" height="72" weight="170" reach="" stance="" first_name="Sai" nick_name="The Boss" last_name="Wang">
<record wins="6" losses="4" draws="1" no_contests="0" />
<born date="1988-01-16" country_code="UNK" country="Unknown" state="" city="" />
<out_of country_code="UNK" country="Unknown" state="" city="" />
</fighter>
<fighter id="0168dd6b-b3e1-4954-8b71-877a63772dec" height="" weight="0" reach="" stance="" first_name="Enrique" nick_name="Wasabi" last_name="Marin">
<record wins="8" losses="2" draws="0" no_contests="0" />
<born date="" country_code="UNK" country="Unknown" state="" city="" />
<out_of country_code="UNK" country="Unknown" state="" city="" />
</fighter>
</fighters>
</profile>';
WITH XMLNAMESPACES(DEFAULT 'http://feed.elasticstats.com/schema/mma/v1/participants-profile.xsd')
SELECT One.fighter.value('@id','uniqueidentifier') AS Fighter_ID
,One.fighter.value('@height','int') AS Fighter_Height
,One.fighter.value('@weight','int') AS Fighter_Weigth
,One.fighter.value('@reach','varchar(100)') AS Fighter_Height
,One.fighter.value('@stance','varchar(100)') AS Fighter_Height
,One.fighter.value('@first_name','varchar(100)') AS Fighter_FirstName
,One.fighter.value('@nick_name','varchar(100)') AS Fighter_NickName
,One.fighter.value('@last_name','varchar(100)') AS Fighter_LastName
,One.fighter.value('record[1]/@wins','int') AS FighterRecord_Wins
,One.fighter.value('record[1]/@draws','int') AS FighterRecord_Draws
,One.fighter.value('record[1]/@no_contests','int') AS FighterRecord_NoContest
,One.fighter.value('born[1]/@date','date') AS FighterBorn_Date
,One.fighter.value('born[1]/@country_code','varchar(10)') AS FighterBorn_CountryCode
,One.fighter.value('born[1]/@country','varchar(100)') AS FighterBorn_Country
,One.fighter.value('born[1]/@state','varchar(100)') AS FighterBorn_State
,One.fighter.value('born[1]/@city','varchar(100)') AS FighterBorn_City
,One.fighter.value('out_of[1]/@country_code','varchar(10)') AS FighterOutOf_CountryCode
,One.fighter.value('out_of[1]/@country','varchar(100)') AS FighterOutOf_Country
,One.fighter.value('out_of[1]/@state','varchar(100)') AS FighterOutOf_State
,One.fighter.value('out_of[1]/@city','varchar(100)') AS FighterOutOf_City
FROM @xml.nodes('/profile/fighters/fighter') AS One(fighter)
```
|
read XML in SQL, no data being pulled
|
[
"",
"sql",
"xml",
""
] |
I have the following two tables:
**SURVEY**
id: INT (PK)
**QUESTIONNAIRE**
id: INT (PK)
[Screenshot of tables](https://i.stack.imgur.com/7C4VL.png)
I want to sellect all surveys along with the number of questionnaires that each survey has so i tried the following query:
```
SELECT s.id, s.title, s.description, count(q.id)
FROM survey s
LEFT OUTER JOIN questionnaire q ON q.survey_id = s.id
GROUP BY s.id
```
**I tried the query in MySQL and it works great.**
The problem is i need to use **MS SQL SERVER 2012** where the same
query does not work.
First i got the following error:
> Msg 8120, Level 16, State 1, Line 1 Column 'survey.title' is invalid
> in the select list because it is not contained in either an aggregate
> function or the GROUP BY clause
.
then i tried:
```
SELECT s.id, s.title, s.description, count(q.id)
FROM survey s
LEFT OUTER JOIN questionnaire q
ON q.survey_id = s.id
GROUP BY s.id, s.title, s.description
```
which reslted in the following error:
> Msg 306, Level 16, State 2, Line 4 The text, ntext, and image data
> types cannot be compared or sorted, except when using IS NULL or LIKE
> operator.
If i remove the s.description (which is TEXT) from the SELECT and GROUP BY the query works but this is no solution.
Any ideas ?
Thank you
|
text is deprecated - try nvarchar(max) or varchar(max)
[ntext, text, and image (Transact-SQL)](https://msdn.microsoft.com/en-us/library/ms187993.aspx)
The left may be the problem but I get you want it.
If nvarchar(max) or varchar(max) does not fix it then try this
```
SELECT s.id, s.title, s.description, sq.cc
FROM survey s
join ( SELECT ss.id, count(qq.id) as cc
FROM survey ss
LEFT OUTER JOIN questionnaire q
ON q.survey_id = s.id
GROUP BY s.id
) sq
on sq.id = s.id
```
|
I think you should learn how Group By and aggregate functions work. This would prove greatly effective in your quest to understanding T-SQL. Here is a link that may help you out.
[Group By Information](http://www.w3schools.com/sql/sql_groupby.asp)
Also, this may not be the case at all but why Text for the description and not varchar in MS SQL Server 2012?
|
Query with left join and count in select works in MySQL but not in MS SQL Server 2012
|
[
"",
"mysql",
"sql",
"sql-server",
"sql-server-2012",
""
] |
Suppose I have a table of strings, like this:
```
VAL
-----------------
Content of values
Values identity
Triple combo
my combo
sub-zero combo
```
I want to find strings which have equal words. The result set should be like
```
VAL MATCHING_VAL
------------------ ------------------
Content of values Values identity
Triple combo My combo
Triple combo sub-zero combo
```
or at least something like this.
Can you help?
|
One method is to use a hack for regular expressions:
```
select t1.val, t2.val
from t t1 join
t t2
on regexp_like(t1.val, replace(t2.val, ' ', '|');
```
You might want the case to be identical as well:
```
on regexp_like(lower(t1.val), replace(lower(t2.val), ' ', '|');
```
|
You could use a combination of SUBSTRING and LIKE.
use charIndex(" ") to split the words up in the substring if thats what you want to do.
|
SQL: Select strings which have equal words
|
[
"",
"sql",
"oracle",
"oracle11g",
""
] |
Let's say I have a simple table:
```
create table foo
{
id INTEGER PRIMARY KEY AUTOINCREMENT,
bar INTEGER
}
```
And I want to insert a new row, such that `id == bar` where value for `id` is chosen by the database, a.k.a. auto-increment.
Something like this:
```
INSERT INTO foo (id, bar) VALUES (NULL, id)
```
Is it possible do this in one statement?
What is the SQL syntax for that?
|
In SQLite you can
```
BEGIN TRANSACTION;
INSERT INTO foo (id, bar) VALUES (NULL, 0);
UPDATE foo SET bar = id WHERE _ROWID_ = last_insert_rowid();
COMMIT;
```
to make sure no other statement gets in the way of your two-statement expression.
|
You can't have [two auto increment fields](https://stackoverflow.com/a/7352543/1045444). You should use a single auto increment field. Given that both fields would always have the same value for every row, there's no reason to have to such fields anyway.
But you can just make trigger which will update another field equal to auto incremented value after inserting row. And delete that trigger when you don't want them to have same values.
```
CREATE TRIGGER update_foo AFTER INSERT ON foo
BEGIN
UPDATE foo SET bar = NEW.id ;
END;
```
When eventually bar will be changed to have not same value as id, then delete trigger
```
DROP TRIGGER update_foo
```
|
Insert into a table and set another column to autoincremented column value
|
[
"",
"sql",
"sqlite",
"insert",
"auto-increment",
""
] |
Is there a case where adding DISTINCT would change the results of a SELECT query that uses a GROUP BY clause?
[Group by and distinct produce similar execution plans.](http://blog.sqlauthority.com/2007/03/29/sql-server-difference-between-distinct-and-group-by-distinct-vs-group-by/)
From my understanding, tables that use a GROUP BY clause can only have columns from the GROUP BY or aggregate functions.
[List of aggregate functions](https://msdn.microsoft.com/en-us/library/ms173454.aspx?f=255&MSPPError=-2147217396) appears to be deterministic and combinations from the GROUP BY would be unique so my assumption is that it would be redundant.
**EDIT 1:** Adding the DISTINCT keyword directly after SELECT. Not anywhere in the query like @lad2025's example: SELECT name, COUNT(DISTINCT col) ... GROUP BY name.
|
You are under no obligation to `SELECT` all the `GROUP BY` columns so in this case it would change the results.
```
SELECT COUNT(*)
FROM sys.objects
GROUP BY schema_id, name
```
--- or
```
SELECT DISTINCT COUNT(*)
FROM sys.objects
GROUP BY schema_id, name
```
|
The groups, as defined by the expressions and columns that appear in the `group by` clause, will be unique in the result set. As long as all those same columns are included in the `select` list then `distinct` will be redundant. As noted by Martin Smith this is not required though.
|
Is SELECT DISTINCT always redundant when using a GROUP BY clause?
|
[
"",
"sql",
"sql-server",
"select",
"group-by",
"distinct",
""
] |
I know how to find the length of the longest string of a column and how to select it. But what I can't figure out is how to query all columns
I tried this in W3School's SQL console
```
SELECT *, MAX(LEN(Address)) as MaxLengthOfAddress
FROM Customers;
```
I get this error message
> Cannot group on fields selected with '\*'.
However, If I just get the maximum address length by itself it works
```
SELECT MAX(LEN(Address)) as MaxLengthOfAddress
FROM Customers;
```
I used the wildcard operator `*` because I wanted to get every column in addition to this maximum length column. I'm not sure why this doesn't work.
|
You need to find the `MAX(LEN(Address))` and then use that to find records with addresses of that length. E.g.,
```
SELECT *
FROM Customers
WHERE LEN(Address) = ( SELECT MAX(LEN(Address))
FROM Customers );
```
You didn't tag your question with a particular RDBMS, but depending on what you are using, it's a sure bet that there are more efficient ways of doing that. But I hope this illustrates the basic concept.
|
You need a subquery in your where clause.
Try like this:
```
SELECT *
FROM Customers
WHERE LEN(Adress) >= (SELECT MAX(LEN(Address))
FROM Customers
)
;
```
|
SQL - How to select all columns of the field with the longest string name
|
[
"",
"sql",
"wildcard",
""
] |
Assuming a DB like this:
```
Date | Attribute1 | Attribute2 | ... | AttributeN
-------------------------------------------------
1 | A | C | ... | ...
1 | B | C | ... | ...
2 | A | A | ... | ...
2 | B | B | ... | ...
2 | A | A | ... | ...
3 | B | B | ... | ...
3 | A | A | ... | ...
4 | B | C | ... | ...
4 | A | A | ... | ...
```
I am trying to find for which unique dates (they are actual `date`s in the real case but I don't think that matters), *ALL* elements of `Attribute1` are equal to their corresponding elements in `Attribute2`. The result for the example data above would be
```
Date
----
2
3
```
Because for each record that has `date` equal to `2` (and the same for `3`) , `Attribute1` is equal to `Attribute2`. `4` is not returned because although the last record in the sample does meet the criterion (since `A` equals `A`), the second last record does not (since `B` does not equal `C`).
I could not work out how to write this query, I was hoping for some aggregate function (shown as `ALL(...)` in the code below) that would allow me to write something like:
```
SELECT Date
FROM myTable
GROUP BY Date
HAVING ALL(Attribute1 = Attribute2)
```
Is there such a function? Otherwise is there a clever way to this using `COUNT` maybe?
|
You can use `HAVING` and `CASE`:
```
SELECT [Date]
FROM #tab
GROUP BY [Date]
HAVING SUM(CASE WHEN Attribute1 = Attribute2 THEN 0 ELSE 1 END) = 0
```
`LiveDemo`
> Otherwise is there a clever way to this using COUNT maybe?
Why not :) Version with `COUNT`:
```
SELECT [Date]
FROM #tab
GROUP BY [Date]
HAVING COUNT(CASE WHEN Attribute1 <> Attribute2 THEN 1 END) = 0
```
`LiveDemo2`
|
Perhaps this:
```
select Date from Test
Except
Select Date from Test where Attribute1 <> Attribute2
```
|
Check if two columns are equal for all rows per group
|
[
"",
"sql",
"sql-server",
"group-by",
"equality",
"having",
""
] |
I have a basic understanding of sql and have built a small database that has to be submitted in 24 hours. I have made a schema in sqlfiddle here
<http://www.sqlfiddle.com/#!9/28fcd>
I need to run a query that will search for a staff member (from table occurrence or teaching) and return the module\_code and module\_title (from table course) for the courses taught by said staff member.
I have spent a day and a half trying to solve this (which probably makes me quite dim) and am now desperate for some help.
The table schema is below. Apologies if this is not the way things are done.
```
CREATE TABLE course (
module_code VARCHAR (10),
module_title VARCHAR (40),
PRIMARY KEY (module_code));
CREATE TABLE teaching (
staff VARCHAR (40),
room VARCHAR (10),
PRIMARY KEY (staff));
CREATE TABLE occurrence (
module_code VARCHAR (10),
Instance VARCHAR (1),
staff VARCHAR (40),
year INT (1),
hours INT (2),
PRIMARY KEY (instance, module_code),
FOREIGN KEY (staff) REFERENCES teaching (staff));
INSERT INTO teaching VALUES
('Louise Ashby','C2-07a'),
('Abdul Razak','C2-09'),
('Brennen Tighe','C2-06'),
('Andrew Parker','C2-04'),
('Tim Goddard','C2-04');
INSERT INTO course VALUES
('CPU4000','Core Skills'),
('CPU4003','Introduction to Programming'),
('CPU4005','Networking Fundamentals');
INSERT INTO occurrence VALUES
('CPU4000','A','Louise Ashby',1,5),
('CPU4000','B',NULL,1,0),
('CPU4000','C',NULL,1,0),
('CPU4003','A','Abdul Razak',1,6),
('CPU4003','B','Brennen Tighe',1,6),
('CPU4003','C','Andrew Parker',1,6),
('CPU4005','A','Tim Goddard',1,0),
('CPU4005','B',NULL,1,0),
('CPU4005','C',NULL,1,0);
```
The SQL i am using is a little like:
SELECT module\_title, module\_code
FROM course, occurrence
WHERE occurrence.staff = 'Louise Ashby';
This tells me that Column 'module\_code' in field list is ambiguous
|
Query is like:
```
select c.* from course c
inner join occurrence o on o.module_code = c.module_code
where o.staff = 'Louise Ashby'
```
Based on your schema. However, in a real world application, you wouldn't use such a schema.
|
```
select
`teaching`.staff,
`course`.module_code,
`course`.module_title
from
`teaching`
inner join
`occurrence` on
`occurrence`.staff = `teaching`.staff
inner join
`course` on
`course`.module_code = `occurrence`.module_code
```
|
SQL SELECT query over 2 tables
|
[
"",
"mysql",
"sql",
""
] |
Two models User and Article have a relation as:
* User *has\_one* Article
* Article *belongs\_to* User
-User has a field called 'status'
-Article has a field called 'thing\_i\_need'
```
class User < ActiveRecord::Base
has_one :article, foreign_key: request_id
# status :integer
end
class Article < ActiveRecord::Base
belongs_to :user, foreign_key: request_id
# thing_i_need :string
end
```
Query: `User.where(status: 'xyz').last.article.thing_i_need`
Currently, two queries are fired to get the 'thing\_i\_need'
Any way to do it in one query ?
Does [this](https://stackoverflow.com/questions/10391266/ruby-on-rails-activerecord-query-using-a-join) help ?
|
You can try this
```
User.joins(:article).where(status: 'xyz').pluck('articles.thing_i_need').last
```
I'd recommend reading [select](http://apidock.com/rails/ActiveRecord/QueryMethods/select) & [pluck](http://apidock.com/rails/ActiveRecord/Calculations/pluck) query methods from the doc, earlier I was trying select in place of pluck and it didn't work.
|
```
Article.includes('user').where('users.status = ? and articals.request_id = users.request_id', 'xyz').first.thing_i_need
```
|
Reduce two SQL queries to one in activerecord maybe using joins
|
[
"",
"mysql",
"sql",
"ruby-on-rails",
"activerecord",
"rails-activerecord",
""
] |
I have to do the below for every teacher.
Given a TeacherId, I want to select all students who have this Teacher and have passed the first semester.
If all the teachers students have passed, I want to call another stored procedure:
```
EXEC AllTeachersStudentsPassedSemester1 @teacherId
```
The tables are as follows:
Teacher
- teacherId
```
Students
-userId
-teacherId
CourseSummarry
-userId
-passedSemester1 (bool)
```
So to get all users for a given teacher I have:
```
SELECT userId
FROM Students
WHERE teacherId = @teacherId
```
How can I test if all the students in that list have passedSemester1 = TRUE, and then call that proc `AllTeachersStudentsPassedSemester1` for that teacher. Confused how I can check if all the students have passed.
I then have to somehow loop through all teachers to do this.
This seems like I have to program this in code rather than sql.
|
This query should give you all of the teachers that did not have a failing student:
```
Select Distinct S.TeacherId
From Students S
Where Not Exists
(
Select *
From CourseSummary C
Where C.UserId In
(
Select S2.UserId
From Students S2
Where S2.TeacherId = S.TeacherId
)
And C.passedSemester1 = 0
)
```
You can then use this in a `CURSOR` to iterate over each entry to execute the procedure:
```
Declare @TeacherId Int
Declare cur Cursor For
Select Distinct S.TeacherId
From Students S
Where Not Exists
(
Select *
From CourseSummary C
Where C.UserId In
(
Select S2.UserId
From Students S2
Where S2.TeacherId = S.TeacherId
)
And C.passedSemester1 = 0
)
Open cur
While (1 = 1)
Begin
Fetch Next From cur Into @TeacherId
If @@Fetch_Status <> 0 Break
Execute AllTeachersStudentsPassedSemester1 @TeacherId
End
Close cur
Deallocate cur
```
|
If I understand your question correctly, you can use a `join` with aggregation to get the list of teachers. Then you would need to use a `cursor` to call a separate stored procedure passing in each teacher's id. Here is the `sql` to get the teachers:
```
select s.teacherid
from students s
join coursesummary cs on s.userid = cs.userid
group by s.teacherid
having count(*) = sum(case when cs.passedSemester1 = 'true' then 1 else 0 end)
```
This presume each `student` record exists in `coursesummary`. If that's not the case, you'd need to use an `outer join` and change the `having` criteria slightly.
As a side note, something seems off with your table design. I would think you'd need a courseid and a different cross reference lookup table. I won't presume to understand your database though.
|
How to check if all of a Teachers students have met a requirement
|
[
"",
"sql",
"sql-server",
""
] |
I want to query data in mysql like:
```
$cid=$_POST["cid"];
$room_id=$_POST["room_id"];
$time=$_POST["time"];
$reuslt=$this->db-query("SELECT * FROM mytable WHERE if($cid is not null){then check cid=$cid} else{don't check} AND if($room_id is not null){then check room_id=$room_id} else{don't check} AND if($time is not null){then check time=$time} else{don't check}");
```
How could I writ the correct sql to query data?
|
So if you wanted to use an SQL if|else statement, look at something like [Using an IF Statement in a MySQL SELECT query](https://stackoverflow.com/questions/8444570/using-an-if-statement-in-a-mysql-select-query), or [If else on WHERE clause](https://stackoverflow.com/questions/15162404/if-else-on-where-clause).
Some other sql answers here look interesting too. However i would caution against overcomplicating.
For this OP its easier to prepare statement you send to DB, rather than overthink it and risk performance drop if massive dataset and poor indexes.
So, if this is more relevant as a php if|else, and you want to keep it as a single line (as opposed to concatenating a string over multiple statements), i would recommend ternary syntax
<https://davidwalsh.name/php-shorthand-if-else-ternary-operators>
For example, something like this should work:
```
$reuslt= $this->db-query("SELECT * FROM mytable WHERE TRUE "
. ( ($cid is not null) ? " AND cid='".$cid."'" : "" )
. ( ($room_id != null) ? " AND room_id='".$room_id."'" : "" )
. ( ($time != null) ? " AND time='" . $time . "'" : "" );
```
The WHERE TRUE is just to make easier to print, though it really would be easier to just create a $sql string variable and prepare the statement over seperate if() statements.
Though i would also stress the need for escaping these values, as you should with all user input.
<http://php.net/manual/en/mysqli.real-escape-string.php>
|
You can use `1=1` as a placeholder in an `IF` function in a `WHERE` clause:
```
$query = "SELECT * FROM mytable
WHERE IF('$cid' != '', cid='$cid', 1=1)
AND IF('$room_id' != '', room_id='$room_id', 1=1)
AND IF('$time' != '', time='$time', 1=1)"
$result=$this->db->query($query);
```
I don't know how your framework handles it, but this code is seriously vulnerable to SQL injection and you should be using prepared queries with parameterization.
|
How to use if else in mysql where clause
|
[
"",
"mysql",
"sql",
"codeigniter",
""
] |
Here is the table:
```
([TeamA],[TeamB],[Win],[date])
('KKR','HYD','KKR',1),
('KKR','MUM','MUM',2),
('RCB','HYD','HYD',3),
('DEL','PUB','PUB',4),
('RR','PUB','RR',4),
('RR','DEL','RR',5),
('RCB','CSK','CSK',6),
('RR','CSK','RR',7),
('CSK','MUM','MUM',7),
('MUM','DEL','MUM',8),
('HYD','PUNE','PUNE',9),
('PUB','DEL','DEL',9),
('KKR','DEL','KKR',10),
('KKR','RCB','KKR',10)
```
The required answer should be the teams who are winning 3 in a row and the count. Here for eg RR and MUM are winning once 3 in a row. KKR has 3 wins however if we see the date column it is not 3 in a row hence KKR should not be in the answer and the output should be
```
RR 1
MUM 1
```
|
My approach (probably it can be done in cleaner way):
```
WITH cte AS
(
SELECT TeamA AS team FROM #tab
UNION
SELECT TeamB FROM #tab
), cte2 AS
(
SELECT c.team
,[opponent] = CASE WHEN c.team = t.teamA THEN t.teamB ELSE t.teamA END
,t.[win]
,t.[day]
,[is_winner] = CASE WHEN c.team = t.[win] THEN 1 ELSE 0 END
FROM cte c
JOIN #tab t
ON c.team = t.teamA
OR c.team = t.teamB
), cte3 AS
(
SELECT team, [day], [is_winner],
r = ROW_NUMBER() OVER (PARTITION BY team ORDER BY [day])
FROM cte2
), cte4 AS
(
SELECT team, Length = MAX(r) - MIN(r) + 1
FROM (SELECT team, r
,rn=r-ROW_NUMBER() OVER (PARTITION BY team ORDER BY r)
FROM cte3
WHERE is_winner = 1) a
GROUP BY team, rn
)
SELECT team, SUM(Length/3) AS [Number_of_hat_tricks]
FROM cte4
WHERE Length >= 3
GROUP BY team;
```
`LiveDemo`
Output:
```
╔══════╦══════════════════════╗
║ team ║ Number_of_hat_tricks ║
╠══════╬══════════════════════╣
║ MUM ║ 1 ║
║ RR ║ 1 ║
╚══════╩══════════════════════╝
```
How it works:
* cte - get all teams
* cte2 - for each team find opponent and check if team wins
* cte3 - add consequitive numbers
* cte4 - calculate length of each island
* final - get the island >= 3 and sum them up (integer division is for counting 6 wins in rows as 2 and 9 in rows as 3,...)
**One final thought:**
Value in in last column has to be unique with the same team:
```
('RR','CSK','RR',7)
('CSK','MUM','MUM',7)
CSK vs RR - 7
CSK vs MUM - 7
```
With current data is impossible to sort it in stable manner. So it should be date with time part:
```
CSK vs RR 2015-12-07 10:00
CSK vs MUM 2015-12-07 21:00 -- now we know that it is the second match
```
|
One more possible way of solving this without using CTE:
```
create table #a
(
teama varchar(10), teamb varchar(10), win varchar(10), dat int)
insert into #a
values
('KKR','HYD','KKR',1),
('KKR','MUM','MUM',2),
('RCB','HYD','HYD',3),
('DEL','PUB','PUB',4),
('RR','PUB','RR',4),
('RR','DEL','RR',5),
('RCB','CSK','CSK',6),
('RR','CSK','RR',7),
('CSK','MUM','MUM',7),
('MUM','DEL','MUM',8),
('HYD','PUNE','PUNE',9),
('PUB','DEL','DEL',9),
('KKR','DEL','KKR',10),
('KKR','RCB','KKR',10);
select
team,
win,
row_number() over (partition by team order by dat) matchnum
into #res
from
(
select teamA team, case when teamA = win then 1 else 0 end as win, dat
from #a
union all
select teamB team, case when teamB = win then 1 else 0 end , dat
from #a
)A
order by team,dat
select
match1.team, count(*)/3 + 1 cntHatricks
from #res match1 join #res match2
on match1.team = match2.team and match2.matchnum = match1.matchnum+1
join #res match3 on match1.team = match3.team and match3.matchnum = match1.matchnum+2
where
match1.win = 1 and match2.win = 1 and match3.win = 1
group by match1.team
```
**OUTPUT**
```
+------+-------------+
| Team | cntHatricks |
+------+-------------+
| MUM | 1 |
| RR | 1 |
+------+-------------+
```
|
How to get three wins in a row
|
[
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
Here is my table
```
Equipmentid Application Value
=========== =========== =====
k001 THK True
k001 BHK False
k001 KHK True
```
Here is what I expected:
```
Equipmentid THK BHK KHK
=========== === === ===
k001 True False True
```
I'm trying to use normal transpose Oracle using max decode but in the end need to mention AS [tablename], I want to dynamically create row to column base on row name, this database will involve very much application. Thank guys
|
Try this one.
```
SELECT EQUIPMENTID,
max(case when APPLICATION = 'THK' then VALUE end) as "THK",
max(case when APPLICATION = 'BHK' then VALUE end) as "BHK",
max(case when APPLICATION = 'KHK' then VALUE end) as "KHK"
FROM [tablename]
group by EQUIPMENTID;
```
|
Hi try using PIVOT,
```
WITH x(equipment_id, application, VALUE )
AS (SELECT 'k001', 'THK', 'TRUE' FROM DUAL UNION ALL
SELECT 'k001', 'BHK', 'FALSE' FROM DUAL UNION ALL
SELECT 'k001', 'KHK', 'TRUE' FROM DUAL UNION ALL
SELECT 'k002', 'KHK', 'FALSE' FROM DUAL UNION ALL
SELECT 'k002', 'THK', 'FALSE' FROM DUAL UNION ALL
SELECT 'k002', 'BHK', 'FALSE' FROM DUAL )
SELECT * FROM
(
SELECT equipment_id, value, application
FROM x
)
PIVOT
(
MAX(value)
FOR application IN ('THK', 'BHK', 'KHK')
) order by equipment_id;
```
Alternatively, if you want to have dynamic column, you can use subquery in the IN clause then use PIVOT XML,but result will be of XML TYPE which i dont know how to extract the values.(just saying) if you want to know more about how to do it dynamically with pl/sql. [Read here](http://technology.amis.nl/2006/05/24/dynamic-sql-pivoting-stealing-antons-thunder/) .[Here's the source](https://asktom.oracle.com/pls/asktom/f?p=100:11:0::NO::P11_QUESTION_ID:5312784100346298561)
```
SELECT * FROM
(
SELECT equipment_id, value, application
FROM x
)
PIVOT XML
(
MAX(value)
FOR application IN (SELECT DISTINCT application from x)
) order by equipment_id;
```
|
How to transpose dynamically in Oracle
|
[
"",
"sql",
"oracle",
"oracle11g",
"transpose",
""
] |
How to display first name, last name and salary of all subordinates from HR on Oracle?
I have:
```
SELECT J.JOB_TITLE, E.FIRST_NAME, E.LAST_NAME, E.SALARY, (SELECT SUM(EMPLOYEES.SALARY) FROM EMPLOYEES)
FROM JOBS J LEFT JOIN EMPLOYEES E ON J.JOB_ID = E.JOB_ID
GROUP BY J.JOB_TITLE, E.FIRST_NAME, E.LAST_NAME, E.SALARY
ORDER BY E.SALARY DESC;
```
But it shows the total salary:
```
SELECT SUM(EMPLOYEES.SALARY) FROM EMPLOYEES
```
Schema:
[](https://i.stack.imgur.com/7AlDI.gif)
Thx.
|
So, if I got this right, you want your last column to be the total salary of all the subordinate employees, both direct and indirect. If so, you can use a `connect by` clause in the subquery to get that information.
Try something like this:
```
SELECT j.job_title,
e.first_name.
e.last_name,
e.salary,
(
SELECT SUM(s.salary)
FROM employees s
START WITH s.manager_id = e.employee_id,
CONNECT BY PRIOR s.employee_id = s.manager_id
) AS total_subordinate_salary
FROM jobs j
LEFT JOIN employees e
ON j.job_id = e.job_id
GROUP BY j.job_title, e.employee_id, e.first_name, e.last_name, e.salary
ORDER BY e.salary DESC NULLS LAST;
```
|
I think you're looking for something like this:
```
SELECT
J.JOB_TITLE,
E.FIRST_NAME,
E.LAST_NAME,
E.SALARY,
(SELECT SUM(EMPLOYEES.SALARY) FROM EMPLOYEES where manager_id = e.employee_id)
FROM
JOBS J LEFT JOIN EMPLOYEES E ON J.JOB_ID = E.JOB_ID
GROUP BY
J.JOB_TITLE, E.FIRST_NAME, E.LAST_NAME, E.SALARY
ORDER BY
E.SALARY DESC;
```
let me know if that's what you're looking for.
|
How to display first name, last name and salary of all subordinates from HR. Oracle
|
[
"",
"sql",
"oracle",
"oracle11g",
""
] |
I'd like to know difference between `rowID` and `rowNUM`
And how to see both of these in our table.
when I execute this:
```
SELECT * FROM emp WHERE rownum=1
```
It returns one query but when I do the same for rowid it says
> inconsistent datatypes: expected ROWID got NUMBER
And even in some of the tables, rownum returns null . Why so?
Please clarify this: rowid vs rownum?(Demo query)
Thank you
EDIT: Require to use alias to display `ROWID` and `ROWNUM`(as they're pseudocolumn)
like:
`SELECT rownum r1, rowid r2 FROM emp`
|
Both, ROWNUM and ROWID are pseudo columns.
**Rowid**
> For each row in the database, the ROWID pseudo column returns the
> address of the row.
An example query would be:
```
SELECT ROWID, last_name
FROM employees
WHERE department_id = 20;
```
More info on rowid here: <https://docs.oracle.com/cd/B19306_01/server.102/b14200/pseudocolumns008.htm>
**Rownum**
> For each row returned by a query, the ROWNUM pseudo column returns a
> number indicating the order in which Oracle selects the row from a
> table or set of joined rows. The first row selected has a ROWNUM of 1,
> the second has 2, and so on.
You can limit the amount of results with rownum like this:
```
SELECT * FROM employees WHERE ROWNUM < 10;
```
More info on rownum here: <https://docs.oracle.com/cd/B19306_01/server.102/b14200/pseudocolumns009.htm>
**Difference**
The actual difference between `rowid` and `rownum` is, that rowid is a permanent unique identifier for that row. However, the rownum is temporary. If you change your query, the rownum number will refer to another row, the rowid won't.
So the ROWNUM is a consecutive number which applicable for a specific SQL statement only. In contrary the ROWID, which is a unique ID for a row.
|
**Rownum (numeric)** = Generated Sequence Number of your output.
**Rowid (hexadecimal)** = Generated automatically at the time of insertion of row.
```
SELECT rowid,rownum fROM EMP
ROWID ROWNUM
----- ----------------------
AAAR4AAAFAAGzg7AAA, 1
AAAR4AAAFAAGzg7AAB, 2
AAAR4AAAFAAGzg7AAC, 3
AAAR4AAAFAAGzg7AAD, 4
AAAR4AAAFAAGzg7AAE, 5
```
|
What is rowID & rowNum (ROWID vs ROWNUM)
|
[
"",
"sql",
"oracle10g",
"rownum",
"rowid",
""
] |
I have following DQL query
```
SELECT
ps.id,
MAX(ps.dueDate) as due_date,
u.firstName as first_name,
u.lastName as last_name,
u.email,
IDENTITY(ps.loanApplication) as loan_application_id,
DATE_DIFF(MAX(ps.dueDate), CURRENT_DATE()) as diff
FROM
Loan\Entity\PaymentSchedule ps
LEFT JOIN
ps.paymentType pt
LEFT JOIN
ps.loanApplication la
LEFT JOIN
la.status s
LEFT JOIN
la.user u
WHERE
pt.slug != :paymentSlug AND s.keyIdentifier = :status AND diff = 14
GROUP BY
ps.loanApplication
```
Which translates to following SQL query
```
SELECT
p0_.id AS id_0,
MAX(p0_.due_date) AS sclr_1,
u1_.first_name AS first_name_2,
u1_.last_name AS last_name_3,
u1_.email AS email_4,
p0_.loan_application_id AS sclr_5,
DATEDIFF(MAX(p0_.due_date), CURRENT_DATE) AS sclr_6
FROM
payment_schedule p0_
LEFT JOIN
payment_type p2_ ON p0_.payment_type_id = p2_.id
LEFT JOIN
loan_application l3_ ON p0_.loan_application_id = l3_.id
LEFT JOIN
loan_application_status l4_ ON l3_.loan_application_status_id = l4_.id
LEFT JOIN
user u1_ ON l3_.user_id = u1_.id
WHERE
p2_.slug <> ? AND l4_.key_identifier = ? AND sclr_6 = 14
GROUP BY
p0_.loan_application_id
```
This gives me following error
```
======================================================================
PDOException
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'sclr_6' in 'where clause'
----------------------------------------------------------------------
```
When i replace WHERE condition
```
WHERE pt.slug != :paymentSlug AND s.keyIdentifier = :status AND diff = 14
```
With
```
WHERE pt.slug != :paymentSlug AND s.keyIdentifier = :status
```
It works perfectly and displays me correct record, i also tried following WHERE condition
```
WHERE pt.slug != :paymentSlug AND s.keyIdentifier = :status AND DATE_DIFF(MAX(ps.dueDate), CURRENT_DATE()) = :days_diff
WHERE pt.slug != :paymentSlug AND s.keyIdentifier = :status HAVING (DATE_DIFF(MAX(ps.dueDate), CURRENT_DATE())) = :days_diff
```
Above WHERE does not work as well, what am i missing here ?
Thanks.
|
If you want to use the alias in your WHERE clause you need a `sub-select`.
```
select *
from
(SELECT
p0_.id AS id_0,
MAX(p0_.due_date) AS sclr_1,
u1_.first_name AS first_name_2,
u1_.last_name AS last_name_3,
u1_.email AS email_4,
p0_.loan_application_id AS sclr_5,
DATEDIFF(MAX(p0_.due_date), CURRENT_DATE) AS sclr_6
FROM
payment_schedule p0_
LEFT JOIN
payment_type p2_ ON p0_.payment_type_id = p2_.id
LEFT JOIN
loan_application l3_ ON p0_.loan_application_id = l3_.id
LEFT JOIN
loan_application_status l4_ ON l3_.loan_application_status_id = l4_.id
LEFT JOIN
user u1_ ON l3_.user_id = u1_.id
) A
WHERE
slug <> ? AND key_identifier = ? AND sclr_6 = 14
```
This is how query is logically processed
```
FROM clause
WHERE clause
SELECT clause
GROUP BY clause
HAVING clause
ORDER BY clause
```
Since `Where` comes before `Select` you cannot use `alias name` in `Where` clause
|
You cannot use an alias (on the final result fields) in the `WHERE` clause; however, at least with MySQL, you may use a `HAVING` clause without needing a `GROUP BY`.
|
Unknown column where clause
|
[
"",
"mysql",
"sql",
"doctrine-orm",
"dql",
""
] |
I have 2 large tables that I am trying to join in order to group the first records based on a field from the second table. The left table has approx.50 mil records of events, the right table has approx.35 mil records of monthly intervals. The monthly intervals are at subjID level, thus I cannot reduce the size of the right table by keeping only start and end dates. Currently it takes about 40 - 60 minutes to perform the join.
I tried to create simple indexes on subjID, eventDate, startDate and endDate, however it did not seem to improve performance (creating the indexes completed in about 5 minutes, join completed in 38 minutes).
Is there any other option I could use to improve processing?
Left Table of events at subjID level:
```
data eventsTable;
input @1 subjID 8.
@10 eventDate date9.;
format eventDate mmddyy10.;
datalines;
101 01AUG2011
101 28AUG2011
101 30AUG2011
101 01SEP2011
101 12SEP2011
101 28SEP2011
102 01JAN2015
102 15JAN2015
102 01FEB2015
102 16FEB2015
;
run;
```
Right Table of monthly intervals at subjID level. I am trying to bring endDate to events if the events occurred between start and end date:
```
data monthlyTable;
input @1 subjID 8.
@10 startDate date9.
@22 endDate date9.;
format startDate endDate mmddyy10.;
datalines;
101 28JUL2011 30AUG2011
101 30AUG2011 28SEP2011
101 28SEP2011 28OCT2011
102 01DEC2014 02JAN2015
102 02JAN2015 02FEB2015
102 02FEB2015 02MAR2015
;
run;
```
Output:
```
proc sql;
create table wantTable as
select a.*,
endDate as monthlyDate
from eventsTable a left join monthlyTable b on
a.subjID = b.subjID
where a.eventDate > b.startDate and a.eventDate <= b.endDate
order by subjID, eventDate;
quit;
```
|
If you have enough memory and you only need the `enddate` from `monthlyTable`, you might find that a format merge is a more efficient way of doing this. However, if both datasets are large, there's only so much optimisation you can hope for as you always have to do at least full read of each.
```
data t_format(keep = fmtname--hlo) /view = t_format;
set monthlytable(keep = subjID startdate enddate) end = eof;
retain fmtname 'myinfmt' type 'i';
length start end $18; /*Increase for IDs longer than 8 digits*/
start = cats(put(subjID,z8.),put(startdate + 1,yymmdd10.));
end = cats(put(subjID,z8.),put(enddate,yymmdd10.));
label = enddate;
output;
if eof then do;
hlo = 'O';
label = .N;
output;
end;
run;
proc format cntlin = t_format;
run;
data want;
set eventstable;
enddate = input(cats(put(subjID,z8.),put(eventdate,yymmdd10.)),myinfmt18.);
format enddate yymmdd10.;
run;
```
Note the use of the `yymmdd10.` and `z8.` formats - these ensure that keys are always the same length, avoiding ambiguity, and that the ranges of lookup values are correctly specified in ascending order when creating the numeric informat `myinfmt`. I suppose, strictly speaking, this is an *informat* merge rather than a *format* merge, but it's the same sort of idea.
If you want to return multiple lookup variables via this approach, you'll need to concatenate them together when defining the format and then split them after applying it.
I would estimate that this approach requires about 1.5GB of memory for the datasets you've specified - i.e. (18 bytes x 2 per date range + 8 bytes for the formatted value) x 35m rows. Depending on the length of your IDs this may differ a bit.
If you need multiple lookup values then you can do a similar thing using a hash merge, but I suspect the format merge is more efficient in this case.
One possible hash merge approach looks like this:
```
data t_lookup /view= t_lookup;
set monthlytable;
by subjID;
if first.subjID then id_range_count = 0;
id_range_count + 1;
run;
data want;
set eventstable;
if _n_ = 1 then do;
if 0 then set monthlytable(keep = subjID startdate enddate); /*Add extra lookup vars here as needed*/
declare hash h(dataset:"t_lookup");
rc = h.definekey("subjID","id_range_count");
rc = h.definedata("startdate","enddate"); /*Add extra lookup vars here as needed*/
rc = h.definedone();
end;
match = 0;
rc = 0;
do id_range_count = 1 by 1 while(rc = 0 and match = 0);
rc = h.find();
match = startdate < eventdate <= enddate;
end;
if match = 0 then call missing(startdate,enddate);
drop rc match id_range_count;
run;
```
|
The best index for your query is a composite index on `monthlyTable(subjId, startDate, endDate)`. I'm not sure if it will be a big improvement in terms of performance in SAS, however.
|
Optimize SAS Proc SQL query
|
[
"",
"sql",
"join",
"optimization",
"sas",
"proc",
""
] |
```
create table #middle
(
A INT,
B INT,
C INT
)
INSERT INTO #middle (A,B,C) VALUES (7,6,2),(1,0,8),(9,12,16),(7, 16, 2),(1,12,8), (9,12,16),(9,12,16),(7, 16, 2),(1,12,8), (9,12,16)
;WITH MIDS
AS (SELECT *,
Row_number()
OVER (
ORDER BY a, b, c DESC )AS rn
FROM #middle)
SELECT *
FROM MIDS
WHERE rn <= (SELECT CASE ( Count(*)%2 )
WHEN 0 THEN ( Count(*) / 2 ) + 1
ELSE ( Count(*) / 2 )
END
FROM MIDS) except (SELECT *
FROM MIDS
WHERE rn < (SELECT ( Count(*) / 2 )
FROM MIDS))
```
The query i have tried works >4 records but not for '3'.Now my question is how should i modify my query so that for 3 records i should get the 2nd record which is the middle most record among them,try to insert only 3 records from above records and help. Thanks in advance.
|
You can use OFFSET and FETCH
```
select *
from #middle
order by a, b, c desc
offset (select count(*) / 2 - (case when count(*) % 2 = 0 then 1 else 0 end) from #middle) rows
fetch next (select 2 - (count(*) % 2) from #middle) rows only
```
|
There are many ways to get the median in SQL. Here is a simple way:
```
select h.*
from (select h.*, row_number() over (order by a, b, c desc) as seqnum,
count(*) over () as cnt
from #highest h
) h
where 2 * rn in (cnt, cnt - 1, cnt + 1);
```
For an even number of records, you will get two rows. You need to decide what you actually want in this case.
|
How to get the middle most record(s) from a group of data in sql
|
[
"",
"sql",
"sql-server",
""
] |
I just started using PL/SQL Developer and I've tried to Google this issue for hours to no avail.
Here is my Query:
```
SELECT "STATION_CODE", "STATUS", COUNT(1)
FROM "Table" "R"
WHERE "STATUS" IN ('LOOKUP CLEAR')
AND
NOT ("REQUEST_TYPE" IN ('Goodnight', 'Freeform', 'CANCEL'))
AND
"CALL_DATE" BETWEEN TO_DATE('07/12/2015','DD/MM/YYYY')
AND
TO_DATE ('13/12/2015 23:59:59','DD/MM/YYYY HH24:MI:SS')
AND
"STATION_CODE" IN ('Code1','Code2','Code3','Code4','Code5','Code6','Code7')
GROUP BY "STATION_CODE", "STATUS";
```
Result:
```
+----------------------------------------+
| Results |
+----------------------------------------+
| Station_Code | Status | Count(1) |
+--------------+--------------+----------+
| Code1 | Filter Clear | 5 |
+--------------+--------------+----------+
| Code2 | Filter Clear | 2 |
+--------------+--------------+----------+
| Code3 | Filter Clear | 5 |
+--------------+--------------+----------+
| Code4 | Filter Clear | 10 |
+--------------+--------------+----------+
| Code5 | Filter Clear | 3 |
+--------------+--------------+----------+
| Code6 | Filter Clear | 8 |
+--------------+--------------+----------+
| Code7 | Filter Clear | 2 |
+--------------+--------------+----------+
```
What I'd like to have is a sum as the very last row of the count.
Something along the lines of:
```
+--------------+--------------+----------+
| Sum | | 35 |
+--------------+--------------+----------+
```
I believe there is a 'having' function that needs to be used but I cant for the life of me figure it out.
I'm not sure if this is relevant but the database connection that I have is a read only view.
Thanks in advance for the help!
|
### It's called `GROUPING SETS`
The simplest solution would be to use [`GROUPING SETS`](https://docs.oracle.com/database/121/DWHSG/aggreg.htm#DWHSG8631) in your `GROUP BY` clause:
```
SELECT DECODE(GROUPING_ID("STATION_CODE"), 0, "STATION_CODE", 'Sum'), "STATUS", COUNT(1)
FROM "Table" "R"
WHERE "STATUS" IN ('LOOKUP CLEAR')
AND NOT ("REQUEST_TYPE" IN ('Goodnight', 'Freeform', 'CANCEL'))
AND "CALL_DATE" BETWEEN TO_DATE('07/12/2015','DD/MM/YYYY')
AND TO_DATE ('13/12/2015 23:59:59','DD/MM/YYYY HH24:MI:SS')
AND "STATION_CODE" IN ('Code1','Code2','Code3','Code4','Code5','Code6','Code7')
GROUP BY GROUPING SETS (("STATION_CODE", "STATUS"), ());
```
This would yield
```
+----------------------------------------+
| Results |
+----------------------------------------+
| Station_Code | Status | Count(1) |
+--------------+--------------+----------+
| Code1 | Filter Clear | 5 |
+--------------+--------------+----------+
| Code2 | Filter Clear | 2 |
+--------------+--------------+----------+
| Code3 | Filter Clear | 5 |
+--------------+--------------+----------+
| Code4 | Filter Clear | 10 |
+--------------+--------------+----------+
| Code5 | Filter Clear | 3 |
+--------------+--------------+----------+
| Code6 | Filter Clear | 8 |
+--------------+--------------+----------+
| Code7 | Filter Clear | 2 |
+--------------+--------------+----------+
| Sum | | 35 |
+--------------+--------------+----------+
```
### Having the sum in every row
Alternatively, what you can do is use a window function (also called analytic function in Oracle) to aggregate an aggregate function. The following query will work:
```
SELECT "STATION_CODE", "STATUS", COUNT(1), SUM(COUNT(1)) OVER()
FROM "Table" "R"
WHERE "STATUS" IN ('LOOKUP CLEAR')
AND NOT ("REQUEST_TYPE" IN ('Goodnight', 'Freeform', 'CANCEL'))
AND "CALL_DATE" BETWEEN TO_DATE('07/12/2015','DD/MM/YYYY')
AND TO_DATE ('13/12/2015 23:59:59','DD/MM/YYYY HH24:MI:SS')
AND "STATION_CODE" IN ('Code1','Code2','Code3','Code4','Code5','Code6','Code7')
GROUP BY "STATION_CODE", "STATUS";
```
And it will yield:
```
+---------------------------------------------------------------+
| Results |
+---------------------------------------------------------------+
| Station_Code | Status | Count(1) | Sum(Count(1)) Over() |
+--------------+--------------+----------+----------------------+
| Code1 | Filter Clear | 5 | 35 |
+--------------+--------------+----------+----------------------+
| Code2 | Filter Clear | 2 | 35 |
+--------------+--------------+----------+----------------------+
| Code3 | Filter Clear | 5 | 35 |
+--------------+--------------+----------+----------------------+
| Code4 | Filter Clear | 10 | 35 |
+--------------+--------------+----------+----------------------+
| Code5 | Filter Clear | 3 | 35 |
+--------------+--------------+----------+----------------------+
| Code6 | Filter Clear | 8 | 35 |
+--------------+--------------+----------+----------------------+
| Code7 | Filter Clear | 2 | 35 |
+--------------+--------------+----------+----------------------+
```
### Calculating the sum separately
Last but not least, you could aggregate the sum of the counts from a nested select. That way, you'll only get the sum:
```
SELECT SUM(c)
FROM (
SELECT COUNT(1) c
FROM "Table" "R"
WHERE "STATUS" IN ('LOOKUP CLEAR')
AND NOT ("REQUEST_TYPE" IN ('Goodnight', 'Freeform', 'CANCEL'))
AND "CALL_DATE" BETWEEN TO_DATE('07/12/2015','DD/MM/YYYY')
AND TO_DATE ('13/12/2015 23:59:59','DD/MM/YYYY HH24:MI:SS')
AND "STATION_CODE" IN ('Code1','Code2','Code3','Code4','Code5','Code6','Code7')
GROUP BY "STATION_CODE", "STATUS"
)
```
In this case [Gordon Linoff's answer](https://stackoverflow.com/a/34300317/521799) is probably better.
|
Remove the `group by` and just do an overall count:
```
SELECT COUNT(1)
FROM "Table" "R"
WHERE "STATUS" IN ('LOOKUP CLEAR') AND
NOT ("REQUEST_TYPE" IN ('Goodnight', 'Freeform', 'CANCEL')) AND
"CALL_DATE" BETWEEN TO_DATE('07/12/2015','DD/MM/YYYY') AND
TO_DATE ('13/12/2015 23:59:59','DD/MM/YYYY HH24:MI:SS') AND
"STATION_CODE" IN ('Code1', 'Code2', 'Code3', 'Code4', 'Code5', 'Code6', 'Code7') ;
```
|
How to sum a count in SQL
|
[
"",
"sql",
"oracle",
"group-by",
""
] |
I'm not sure if I'm asking this right, but I am trying to have 1 row contain all the data for each "policy". The problem is, only 1 "insured name" is given per row.
Example table:
[](https://i.stack.imgur.com/WFKws.png)
I need to get the following result:
[](https://i.stack.imgur.com/K8KBm.png)
How would I go about doing this?
---EDIT---
If there is only one insured, I would want insuredName2 to be NULL
|
I added effective date to the query as I could see a composite primary key including both policy number and effective date.
This assumes a view on the data would be acceptable with changing existing table structure and data.
```
SELECT a.PolicyNumber, a.effecitveDate a.insuredName as InsuredName1,
b.insuredName as InsuredName2
FROM table a
INNER JOIN table b
ON a.policyNumber = b.policyNumber
and A.effectiveDate = b.effectiveDate
```
Be sure to change `table` to be your `tablename` having this data.
Also if you want to ensure one way matches only have `and a.insuredName > B.InsuredName` on the join. This was added to this per an excellent comment by jbrooks.
|
I believe you want to use the following in some fashion:
```
SELECT DISTINCT a.insuredName, b.insuredName
FROM table a
INNER JOIN table b
ON a.policyNumber = b.policyNumber
```
if effective date is also a consideration:
```
...
On a.policyNumber = b.policyNumber
And a.effectiveDate = b.effectiveDate;
```
|
Combine columns a, b, c if column x is duplicate record - SQL
|
[
"",
"sql",
"netezza",
""
] |
My Database class is this, when i call `deleteEntry`, it does not remove 0 index , this is database class method
```
public int deleteEntry(String id)
{
SQLiteDatabase db = dbHelper.getWritableDatabase();
//String id=String.valueOf(ID);
String where="ID=?";
int numberOFEntriesDeleted= db.delete("TIME", where, new String[]{id}) ;
Toast.makeText(context, "Number of Entry Deleted Successfully : "+numberOFEntriesDeleted, Toast.LENGTH_LONG).show();
return numberOFEntriesDeleted;
}
```
this is my `onItemClickListener`
```
list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("Clicked item id", " " + id);
// data.remove(id);
String row = (String.valueOf(id));
data.deleteEntry(row);
```
|
You can try like this:
```
//---deletes a particular entry---
public int deleteEntry(String id)
{
SQLiteDatabase db = dbHelper.getWritableDatabase();
return db.delete("TIME", "ID = " + id, null) ;
}
```
By the way, make sure "TIME" is your tablename and you also close the database.
|
Try passing the position instead of an id:
```
list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("Clicked item id", " " + id);
Log.d("Clicked item position", " " + position);
String row = (String.valueOf(position)); // the change is here
data.deleteEntry(row);
}
```
After you try this, look at the logs you get and try to figure out which value (id or position) are better. Anyway, I suppose you should store the database ID of each item you are displaying somewhere, so that you will not rely only on the position inside your list (once any item is deleted from your table, this will not work) since the ID's will not be sequential.
|
delete zero index of listview which populated from database Android
|
[
"",
"android",
"sql",
"database",
"listview",
""
] |
I am using MS SQL Server 2012 Express Advanced Edition.
My current table structure of one of the accounts table with data is as follows.
```
PARTY DEBIT CREDIT
----------------------------------------
A 1000 NULL
B NULL 2500
C 2000 NULL
A NULL 5000
B 3500 NULL
A 10000 NULL
A 4500 NULL
```
I want to achieve following query result.
```
PARTY DEBIT CREDIT BALANCE
-----------------------------------------------
A 1000 NULL 10500
B NULL 2500 1000
C 2000 NULL 2000
A NULL 5000 NULL
B 3500 NULL NULL
A 10000 NULL NULL
A 4500 NULL NULL
```
I want total closing balance of a party occuring just once against that party name, not repeating balance on the same party.
**For Example, Closing balance of PARTY A, will be 10500, and PARTY A appears multiple times, so I want closing balance to appear with only first record of PARTY A as shown in desired result. And so on with other parties.**
In short, **I want closing balance to appear only once against party name** irrespective of the multiple appearance of that party.
I tried with following query but it gives balance on each occurrence of party.
```
select
PARTY,
DEBIT,
CREDIT,
(select PARTY,SUM(DEBIT)-SUM(CREDIT) from ACCOUNTS where PARTY=A.PARTY group by PARTY) as BALANCE
from
ACCOUNTS A
```
|
If you have some column to maintain the ordering, you could try an analytic function along these lines: get the total for the group (party), then use that as a subquery to display only the balance for the first item in the group. I tried this with Postgresql, you would need to check the syntax for your dbms.
Inner query:
```
SELECT id, party, debit, credit
,SUM(CASE WHEN debit IS NULL THEN -credit ELSE debit END) OVER (PARTITION BY party ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) balance
,ROW_NUMBER() OVER (PARTITION BY party ORDER BY id) AS row_number
FROM accounts;
```
Result:
```
id | party | debit | credit | balance | row_number
----+-------+-------+--------+---------+------------
1 | A | 1000 | | 10500 | 1
4 | A | | 5000 | 10500 | 2
6 | A | 10000 | | 10500 | 3
7 | A | 4500 | | 10500 | 4
2 | B | | 2500 | 1000 | 1
5 | B | 3500 | | 1000 | 2
3 | C | 2000 | | 2000 | 1
```
Wrapped:
```
SELECT party, debit, credit
,CASE WHEN row_number = 1 THEN balance ELSE NULL END AS balance
FROM (SELECT id, party, debit, credit
,SUM(CASE WHEN debit IS NULL THEN -credit ELSE debit END) OVER (PARTITION BY party ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) balance
,ROW_NUMBER() OVER (PARTITION BY party ORDER BY id) AS row_number
FROM accounts) x
ORDER BY id;
```
Result:
```
party | debit | credit | balance
-------+-------+--------+---------
A | 1000 | | 10500
B | | 2500 | 1000
C | 2000 | | 2000
A | | 5000 |
B | 3500 | |
A | 10000 | |
A | 4500 | |
```
|
What you want to achieve doesn't make sense to me. But if you still want to do that, then you need to have a primary key in your balance table. For the example I'm taking ID field of type int as a primary key.
Using below sql query you can achieve your desired result:
```
SELECT A.PARTY, A.DEBIT, A.CREDIT, B.BALANCE FROM BALANCE A
LEFT OUTER JOIN
(SELECT MIN(ID) AS ID, PARTY, (ISNULL(SUM(DEBIT), 0) - ISNULL(SUM(CREDIT),0)) AS BALANCE FROM BALANCE GROUP BY PARTY) B
ON A.ID = B.ID
ORDER BY A.ID
```
[Sql Fiddle](http://sqlfiddle.com/#!9/b6323/5)
|
SQL Server Query For Balance to appear only once if party name occurs multiple times
|
[
"",
"sql",
"sql-server-2012",
""
] |
I have a time interval in the format '88:52:57'
I need to convert it into a decimal hours in the format 88.88
How can I do this?
I have the data initially loaded as a varchar
|
You can use left, right and substring to extract the values and then do some calculations.
```
declare @S varchar(8) = '88:52:57';
select left(@S, 2) + substring(@S, 4, 2)/60.0 + right(@S, 2)/60.0/60.0;
```
If you not always have two digit values you can use parsename to get the values instead.
```
declare @S varchar(20) = '088:052:057';
select parsename(S.X, 3) + parsename(S.X, 2)/60.0 + parsename(S.X, 1)/60.0/60.0
from (select replace(@S, ':', '.')) as S(X)
```
|
Try this, solution is based on conversions, making it safe, if the format is always (h)h:mi:ss:
```
DECLARE @S varchar(8) = '88:52:57';
SELECT
CAST(REPLACE(left(@S, 2), ':', '') as int)+
CAST(CAST(CAST('0:'+RIGHT(@S, 5) as datetime) as decimal(10,10)) * 24 as decimal(2,2))
```
Result:
```
88.88
```
|
Convert time interval into decimal hours in SQL Server
|
[
"",
"sql",
"sql-server",
""
] |
I am inserting data in table with current system time like
`System.currentTimeMillis()`. So, while getting data I need to take last 3 hours data only.
Following link not help me. because this link using specific date format which I don't have.
[Getting data according to last hours from sqlite](https://stackoverflow.com/questions/33254848/getting-data-according-to-last-hours-from-sqlite)
Here Is my Query but seems it's not working.
```
SELECT * FROM Table1 where timestamp >= datetime('now','-3 hours')
```
Where timestamp is nothing but current system time while inserting.
Please give me any reference or hint.
|
You can get TimeStamp of Time 3 Hours back using following
```
Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR, -3);
Date threeHourBack = cal.getTime();
```
Then you can pass `threeHourBack.getTime()` to the query.
Or You can do this in SQLite
```
SELECT * FROM Table1 where datetime(timestamp) >=datetime('now', '-3 Hour')
```
|
there could be other methods. but I think this will work for you.
```
SELECT * FROM Table1 where timestamp >= (System.currentTimeMillis()-108000000)
```
subtract 3 hours from current time and and search for time grater than that.
|
How to get Last 3 hours data from SQLite
|
[
"",
"android",
"sql",
"select",
"timestamp",
""
] |
I'm having a hard time solving this, i hope someone can help me out with some tips or advice.
I have a Table in SQL with 3 columns:
```
Pencil Sales Notebook Sales Pen Sales
1 2 3
9 5 6
7 8 9
```
I made a query using "Union all" with the sum of each column.
My query looks like this:
```
select sum(pencilsales) from table1 union all
select sum(notebooksales) from table1 union all
select sum(pensales) from table1
```
and it gives me the following:
```
(No Column Name)
17
15
18
```
But i wanna know if there's a way of sorting this new query by using "desc" or something like that and to add a new column saying which one is each row, like this:
```
Sales Name
18 Pen Sales
17 Pencil Sales
15 Notebook Sales
```
Hope you can help me out with ideas and thank you in advance :)
|
```
select * from
(
select 'Pencil Sales' as Name, sum(pencilsales) as sales from table1
union all
select 'Notebook Sales', sum(notebooksales) from table1
union all
select 'Pen Sales', sum(pensales) from table1
) t order by sales desc
```
|
This is a pretty good candidate for UNPIVOT
```
SELECT
SUM(Sales) Sales,
[Name]
FROM Table1
UNPIVOT (
Sales
FOR [Name] IN ([pencilsales], [notebooksales], [pensales])
) up
GROUP BY [Name]
```
|
Merge multiple columns in one single column SQL
|
[
"",
"sql",
"sql-server",
"sql-server-2008",
"sql-server-2005",
""
] |
In SQL,I am trying to compare two numbers in the same field. Both numbers contain different information, but for some technical reason they are same. The problem is when exist one sub-string of length 5 and another of length 4 and the last 4 digits of both are same.I want to get the first one with length 5.
Example:
```
--------------------------------
|ID | Number| Description |
---------------------------------
| 1 | 12345 | Project X,Ready |
---------------------------------
| 2 | 2345 | Project X,onDesign |
---------------------------------
```
I should always get 12345(or biggest one) if exist numbers with last 4 digits same. Is there any CASE or CTE statement which can give me an easy resolution for this issue?
|
Try this:
```
SELECT Id
,Number
,Description
FROM (
SELECT Id
,Number
,Description
,rank() OVER (PARTITION BY right(cast([Number] AS VARCHAR(20)), 4) ORDER BY Number DESC) AS Ranking
FROM YourTable
) InnerTable
WHERE ranking = 1
```
|
So you need to join using last 4 digits. You could do this by using simple `MOD` operator. It's used as a percentage sign in SQL Server.
```
SELECT 12345 % 10000;
```
This outputs `2345`. Exactly what we are looking for.
So we could build the following query to use that calculation:
```
DECLARE @Test TABLE
(
ID INT
, Number INT
, Description VARCHAR(500)
);
INSERT INTO @Test(ID, Number, Description)
VALUES (1, 12345, 'Project X,Ready')
, (2, 2345, 'Project X,onDesign');
SELECT T1.*
FROM @Test AS T1
INNER JOIN @Test AS T2
ON T2.Number = T1.Number % 10000
WHERE T2.Number <> T1.Number;
```
Output:
```
╔════╦════════╦═════════════════╗
║ ID ║ Number ║ Description ║
╠════╬════════╬═════════════════╣
║ 1 ║ 12345 ║ Project X,Ready ║
╚════╩════════╩═════════════════╝
```
Note that I've added `WHERE T2.Number <> T1.Number`. It eliminates equal numbers, because `SELECT 2345 % 10000` is `2345` as well.
### Update
This could be done using `ROW_NUMBER()`
```
;WITH Data (ID, Number, Description, RN)
AS (
SELECT ID
, Number
, Description
, ROW_NUMBER() OVER (PARTITION BY Number % 10000 ORDER BY Number DESC)
FROM @Test
)
SELECT *
FROM Data
WHERE RN = 1;
```
This will do the classic row\_number stuff. It will partition windows by `Number % 10000`, which means that 12345 and 2345 will fall under same window and the highest number will always come first.
|
Compare two number SQL
|
[
"",
"sql",
"sql-server",
"case",
"common-table-expression",
""
] |
I've been trying to split a string value in my query to return the first part of a two part postcode in a new column. Some values have only the first part, and some have both. After a bit of searching I found this code:
```
SELECT
TblPLSSU.PLSSUPostcode
,SUBSTRING(TblPLSSU.PLSSUPostcode, 1, CHARINDEX(' ', TblPLSSU.PLSSUPostcode)) AS PCode
FROM
TblPostcodes
```
This happily splits the values that have two parts to the postcode but it seems to be ignoring the single part post codes.
For example, values for TblPLSSU.PLSSUPostcode might be:
```
EH1 1AB
EH2
```
I want to return the values
```
EH1
EH2
```
But with the code above I am only getting EH1
Thanks
Eils
|
Use `case` to pick up post codes as-is when they don't have a space separated value.
```
SELECT
PLSSUPostcode
,case when CHARINDEX(' ', PLSSUPostcode) > 0
then SUBSTRING(PLSSUPostcode, 1, CHARINDEX(' ', PLSSUPostcode))
else PLSSUPostcode end AS PCode
FROM
TblPostcodes
```
|
Use `case` as well:
```
SELECT TblPLSSU.PLSSUPostcode,
(CASE WHEN TblPLSSU.PLSSUPostcode LIKE '% %'
THEN SUBSTRING(TblPLSSU.PLSSUPostcode, 1, CHARINDEX(' ', TblPLSSU.PLSSUPostcode))
END) AS PCode
FROM . . .
```
|
SQl string split (parse) on space where some field values have no space
|
[
"",
"sql",
"sql-server-2008",
""
] |
I don't want the query to select anything if the where clause is not fullfilled, but maybe i am missing something. Following is the query i am using
```
SELECT one.id_user, integration, data
FROM tableOne one
LEFT JOIN tableTwo two ON two.id_user = one.id_user
AND two.integration IN ('office', 'Office')
WHERE one.state='NEW' OR one.state='PAUSED'
AND two.integration IN ('office', 'Office')
GROUP BY one.id_user
```
The record is inserted in the required table with integration "SomeValue" and not "office" or "Office" which means the where claus should not be true and the query should not return anything, but it does. It returns id\_user and rest of the fields as null.
But i don't it to select even the id\_user if the integration is not "office" or "Office".
Can someone tell me please what am i doing wrong?
|
From what I see you made 2 errornous assumptions there.
The first is the sql statement is NOT a left join. As strange as it sounds. The reason behind this is that you use the 2nd table that is joined via left join in the where statement. This transforms the whole left join into an inner form instead.
The second assumption is that
```
one.state='NEW' OR one.state='PAUSED' AND two.integration IN ('office', 'Office')
```
does not display anything if two.integration is not (O)office. The and is stronger as the or which means in effect you have
```
(one.state='NEW') OR (one.state='PAUSED' AND two.integration IN ('office', 'Office'))
```
Thus if state is NEW then it does not matter what integration has as value.
You should correct this to:
```
((one.state='NEW') OR one.state='PAUSED') AND two.integration IN ('office', 'Office')
```
to get the desired result there.
Then you still have the problem with inner join and left join though. In essence you would have to move the two.integration part into the left join on part if you really WANT a left join there (which your problem description does not sound like). If you want an inner join instead you should rename the join part and put all of the where parts into the on part of the inner join:
```
SELECT one.id_user, integration, data
FROM tableOne one
INNER JOIN tableTwo two ON two.id_user = one.id_user
AND two.integration IN ('office', 'Office')
AND (one.state='NEW' OR one.state='PAUSED')
GROUP BY one.id_user
```
|
Try this:
```
SELECT one.id_user, integration, data
FROM tableOne ONE
INNER JOIN tableTwo two ON two.id_user = one.id_user
WHERE one.state IN ('NEW', 'PAUSED') AND two.integration IN ('office', 'Office')
GROUP BY one.id_user;
```
|
How can i use left join in mysql
|
[
"",
"mysql",
"sql",
"select",
"join",
""
] |
Sorry I don't have better words to title my questions but essentially I am looking for an implementation of CASE/AND...OR statement in the filter condition where if the value of the particular ID is NOT NULL and greater than 0, then only the condition for that ID would be considered otherwise the condition for that ID need not be used at all.
Example 1:
```
select emp_id, cust_id, date_id
from employee a
join customer l
on a.id = l.id
join time_table ACT
on a.join_date_id = ACT.date_id
where a.emp_id = 1
and l.cust_id in (2, 3)
and ACT.date_id >= to_char((sysdate - EXTRACT(DAY FROM (SYSDATE))) - 90, 'DD-MON-YYYY')
and ACT.date_id <= to_char(sysdate - EXTRACT(DAY FROM (SYSDATE)), 'DD-MON-YYYY')
and a.sub_emp_id = CASE WHEN @sub_emp_id IS NOT NULL AND @sub_emp_id > 0 THEN @sub_emp_id WHEN @sub_emp_id IS NULL THEN @sub_emp_id ELSE @sub_emp_id END -- where condition is, if sub_emp_id is not null and if sub_emp_id > 0 then use the value of sub_emp_id otherwise if sub_emp_id is NULL, then don't use the condition for sub_emp_id altogether.
```
Example 2 -
```
select emp_id, cust_id, date_id
from employee a
join customer l
on a.id = l.id
join time_table ACT
on a.join_date_id = ACT.date_id
where (a.emp_id = 1
and l.cust_id in (2, 3)
and ACT.date_id >= to_char((sysdate - EXTRACT(DAY FROM (SYSDATE))) - 90, 'DD-MON-YYYY')
and ACT.date_id <= to_char(sysdate - EXTRACT(DAY FROM (SYSDATE)), 'DD-MON-YYYY')
and a.sub_emp_id > 0)
OR
(a.emp_id = 1
and l.cust_id in (2, 3)
and ACT.date_id >= to_char((sysdate - EXTRACT(DAY FROM (SYSDATE))) - 90, 'DD-MON-YYYY')
and ACT.date_id <= to_char(sysdate - EXTRACT(DAY FROM (SYSDATE)), 'DD-MON-YYYY')) -- where condition is, "if sub_emp_id is not null and if sub_emp_id > 0" then use the value of sub_emp_id otherwise "if sub_emp_id is NULL, then don't use the condition for sub_emp_id altogether".
```
|
I think you were shooting for this:
```
case
when @sub_emp_id > 0 /* not null is also implied */
then case when a.sub_emp_id = @sub_emp_id then 1 else 0 end
else 1
end = 1
```
And I think these are equivalent alternatives:
```
not (@sub_emp_id > 0 and a.sub_emp_id <> @sub_emp_id)
coalesce(@sub_emp_id, 0) <= 0 or a.sub_emp_id = @sub_emp_id
```
|
If I understand you correctly, you'll want your filter on `sub_emp_id` to look like this:
```
...
and (@sub_emp_id is null or
@sub_emp_id <= 0 or
a.sub_temp_id = @sub_emp_id)
```
|
SQL - CASE statement in filter with optional use
|
[
"",
"sql",
"oracle",
"case",
"where-clause",
""
] |
Table schema:
```
CREATE TABLE TRANSACTIONDETAILS
(
TransNo CHAR(15),
Serial INT,
Project CHAR(3)
)
```
Dataset:
```
+-----------------+--------+---------+
| TransNo | Serial | Project |
+-----------------+--------+---------+
| A00000000000001 | 1 | 100 |
| A00000000000001 | 2 | 100 |
| A00000000000002 | 1 | 100 |
| A00000000000002 | 2 | 101 |
| A00000000000003 | 1 | 200 |
| A00000000000003 | 2 | 200 |
| A00000000000003 | 3 | 101 |
| A00000000000004 | 1 | 101 |
| A00000000000004 | 2 | 101 |
| A00000000000005 | 1 | 100 |
| A00000000000005 | 2 | 200 |
+-----------------+--------+---------+
```
I want to select rows those have different project for same TransNo.
Expected output:
```
+-----------------+--------+---------+
| TransNo | Serial | Project |
+-----------------+--------+---------+
| A00000000000002 | 1 | 100 |
| A00000000000002 | 2 | 101 |
| A00000000000003 | 1 | 200 |
| A00000000000003 | 2 | 200 |
| A00000000000003 | 3 | 101 |
| A00000000000005 | 1 | 100 |
| A00000000000005 | 2 | 200 |
+-----------------+--------+---------+
```
I am using SQL Server 2012 and later.
Thanks.
|
You can use subquery to get the list of `TransNo` that have more than one distinct project and then filter initial list only by results from subquery:
```
SELECT TransNo, Serial, Project
FROM TRANSACTIONDETAILS
WHERE TransNo IN (
SELECT TransNo
FROM TRANSACTIONDETAILS
GROUP BY TransNo
HAVING COUNT(DISTINCT Project) > 1 -- only select TransNo that have more than
-- one distinct project
)
```
Here is [SQL Fiddle](http://sqlfiddle.com/#!6/86fc8/5/0)
|
What you'll want to do is get a table with the duplicates.
`SELECT
TransNo,
Project
FROM TRANSACTIONDETAILS
GROUP BY TransNo, Project
HAVING COUNT(1) > 1`
then you'll want to join back to the table. Here's the complete query:
`SELECT
A.TransNo, A.Serial, A.Project
FROM TRANSACTIONDETAILS A
INNER JOIN (
SELECT
TransNo,
Project
FROM TRANSACTIONDETAILS
GROUP BY TransNo, Project
HAVING COUNT(DISTINCT Project) > 1
) B
ON A.TransNo = B.TransNo`
|
Complex SELECT Operation in SQL Server 2012 and later
|
[
"",
"sql",
"sql-server-2012",
""
] |
I know that SQL query will use query cache to receive data instead of reprocess all of the data. Here the question I would like to ask,
I working with a server of database and I'm one of the developer that working on it and I need to do performance testing on queries that i handling
If I clear the query cache
example using `FLUSH QUERY CACHE;` or `RESET QUERY CACHE;`,
will it affect others developer or it only clears away my local query cache?
If it will affect others, is there any way to clear locally or allow my query won't use the query cache for testing
|
Two clarifications to begin with:
* MySQL query cache is a server-side feature, there's no such thing as "local cache". You're probably confused by the `LOCAL` keyword in `FLUSH` command. As [docs](https://dev.mysql.com/doc/refman/5.7/en/flush.html) explain it's just an alias for `NO_WRITE_TO_BINLOG` (thus it's related to replication and "local" means "this server").
* MySQL will only return cached data if you've enabled the feature and either made it default or opted-in with the `SQL_CACHE` hint. In my experience, most servers do not have it by default.
Let's now answer your question. At [The MySQL Query Cache](https://dev.mysql.com/doc/refman/5.7/en/query-cache.html) we can read:
> The query cache is shared among sessions, so a result set generated by
> one client can be sent in response to the same query issued by another
> client.
Which makes sense: a cache that cannot reuse stored data is not as useful.
I don't know what you want to test exactly. Your data should always be fresh:
> The query cache does not return stale data. When tables are modified,
> any relevant entries in the query cache are flushed.
However you might want to get an idea of how long the query takes to run. You can always opt out with [the `SQL_NO_CACHE` keyword](http://dev.mysql.com/doc/refman/5.7/en/query-cache-in-select.html):
> The server does not use the query cache. It neither checks the query
> cache to see whether the result is already cached, nor does it cache
> the query result.
Just take into account that a query that runs for the second time might run faster even without cache because part of the data segments might be already loaded into RAM.
|
Try using the SQL\_NO\_CACHE option in your query.This will stop MySQL caching the results
```
SELECT SQL_NO_CACHE * FROM TABLE
```
|
SQL Query Cache
|
[
"",
"mysql",
"sql",
"caching",
""
] |
I'm trying to get the results from a table such that they are limited by the number of similar field values. For example, here are some sample records:
```
FieldValue (nvarchar)
----------
id1/mode3/path
id2/mode2/path
id3/mode3/path
id4/mode1/path
id5/mode3/path
id6/mode2/path
id7/mode2/path
id8/mode3/path
```
In which case, I only want max 2 records for each mode, so the results should be:
```
id1/mode3/path
id2/mode2/path
id3/mode3/path
id4/mode1/path
id6/mode2/path
```
How can I do this in TSQL (SQL Server 2012)?
**[Update]** Note: id, mode and path are not separate fields. They're a concatenated text value (e.g. "id1/mode3/path") in a field named FieldValue.
|
You can use windowed function and string manipulation function to split data:
```
WITH cte AS
( SELECT
FieldValue
,[id] = LEFT(FieldValue, CHARINDEX('/', FieldValue)-1)
,[mode] = SUBSTRING(FieldValue,
CHARINDEX('/', FieldValue)+1,
CHARINDEX('/',RIGHT(FieldValue,LEN(FieldValue)
-CHARINDEX('/', FieldValue)))-1)
FROM #tab
), cte2 AS
(
SELECT FieldValue, r = ROW_NUMBER() OVER (PARTITION BY mode ORDER BY id)
FROM cte
)
SELECT FieldValue
FROM cte2
WHERE r <= 2
ORDER BY FieldValue;
```
`LiveDemo`
Output:
```
╔════════════════╗
║ FieldValue ║
╠════════════════╣
║ id1/mode3/path ║
║ id2/mode2/path ║
║ id3/mode3/path ║
║ id4/mode1/path ║
║ id6/mode2/path ║
╚════════════════╝
```
|
Lad2025's answer does the job, but I would consider improving your table design (schema), if possible.
In order to avoid computing those substrings and ordering based on it (it is expensive for large data), you can add new columns to the table. They can be computed when FieldValue is inserted or, if this is not possible, added as persisted computed columns:
```
id NVARCHAR(10) AS LEFT(FieldValue, CHARINDEX('/', FieldValue)-1) PERSISTED,
mode NVARCHAR(10) AS SUBSTRING(FieldValue,
CHARINDEX('/', FieldValue)+1,
CHARINDEX('/',RIGHT(FieldValue,LEN(FieldValue)
-CHARINDEX('/', FieldValue)))-1) PERSISTED
```
Thus, the query is greatly simplified:
```
;WITH cte AS
(
SELECT FieldValue, r = ROW_NUMBER() OVER (PARTITION BY mode ORDER BY id)
FROM yourtable
)
SELECT FieldValue
FROM cte
WHERE r <= 2
ORDER BY FieldValue;
```
This design also allows to index added columns to obtain greater performance.
|
Limit results by field value using TSQL
|
[
"",
"sql",
"sql-server",
"t-sql",
""
] |
```
Create Table Billing3
(
billingId int primary key,
FoodCharge float DEFAULT 0,
DoctorCharge float DEFAULT 0,
TestCharge float DEFAULT 0,
OperationCharge float DEFAULT 0,
RoomCharge float DEFAULT 0,
Total float DEFAULT (FoodCharge + DoctorCharge + TestCharge + OperationCharge + RoomCharge)
)
```
|
Alternatively, you can set up a MySQL [insert trigger](http://www.w3resource.com/mysql/mysql-triggers.php). But usually, you want to keep calculations in queries as you save on storage and avoid maintenance on a programming object. Plus, if one of the charges updates values, you would then need an update trigger.
```
USE `databasename`;
DELIMITER
$$
CREATE TRIGGER `TotalCalculation`
BEFORE INSERT
ON `Billing3` FOR EACH ROW
-- Edit trigger body code below this line. Do not edit lines above this one
BEGIN
SET NEW.Total = NEW.FoodCharge + NEW.DoctorCharge + NEW.TestCharge +
NEW.OperationCharge + NEW.RoomCharge;
END
$$
```
|
MySQL does not support calculated columns. You can use a view for this purpose:
```
create view v_billing3 as
select b.*,
(FoodCharge + DoctorCharge + TestCharge + OperationCharge + RoomCharge) as total
from billing3 b;
```
Also, don't store numbers as floating points. Instead, use the fixed point type, `decimal`, for this purpose.
|
How to create table having one column as sum of other columns?
|
[
"",
"mysql",
"sql",
"database",
""
] |
We're trying to run an outer join between table A on both tables B and C but get the error:
> ORA-01417: a table may be outer joined to at most one other table
How can we get this to work?
Query:
```
select a.xxx, a.yyy, b.col1, c.col1 from a, b, c
where
a.xxx = b.xxx (+) and
a.yyy = b.yyy (+) and
a.xxx = c.xxx (+) and
a.yyy = c.yyy (+)
```
|
Please refrain from using comma in the from clause and use the JOIN clause instead.
Try using this:
```
select a.xxx, a.yyy, b.col1, c.col1
from a LEFT JOIN b ON a.xxx = b.xxx AND a.yyy = b.yyy
LEFT JOIN c ON a.xxx = c.xxx AND a.yyy = c.yyy
```
|
Use proper explicit `join` syntax. I think the following is probably what you want to do:
```
select a.xxx, a.yyy, b.col1, c.col1
from a left join
b
on a.xxx = b.xxx and a.yyy = b.yyy left join
c
on a.xxx = c.xxx and a.yyy = c.yyy;
```
|
Outer join between three tables causing Oracle ORA-01417 error
|
[
"",
"sql",
"oracle",
"outer-join",
""
] |
I have **users** and **message\_threads** tables.
```
thread_message tables
Id | ToUserId | FromUserId
----------------------------------
1 | 1 | 2
2 | 2 | 3
users Table
Id | Name
-----------------
1 | Ali
2 | Mahdi
3 | Hossein
```
`Ali` want to get all records from `thread_message` that his `Id` is in the one of`ToUserId` or `FromUserId` and get Name of other user pair(In this example `Mahdi`).
Ali sends his `Id` when request records.
What's **SELECT** & **JOIN** statement for this problem?
In this example result should be
```
(Id ,ToUserId, FromUserId, Name)
(1, 1, 2, Mahdi)
```
|
```
(select t.*, u.Name from thread_message t left join users u on FromUserId=u.Id where ToUserId=1)
union
(select t.*, u.Name from thread_message t left join users u on ToUserId=u.Id where FromUserId=1)
```
|
Try this:
```
SELECT T.Id,
T.ToUserId,
T.FromUserId,
(CASE WHEN T.ToUserId = tu.Id THEN fu.Name WHEN T.FromUserId = tu.Id THEN tu.Name ELSE '' END) Name
FROM thread_message T
LEFT OUTER JOIN users tu ON T.ToUserId = tu.Id
LEFT OUTER JOIN users fu ON T.FromUserId = tu.Id
WHERE 1 IN (T.ToUserId, T.FromUserId);
```
|
Select and join from to tables in mysql
|
[
"",
"mysql",
"sql",
"database",
"select",
"join",
""
] |
Below is my query:
**select c1, c2, c3, c4, c5 from table1 where c1 =0** //Condition 1
**AND c2="abc"** //Condition 2
**AND c3="xxx"** //Condition 3
**AND c4 = 5** //Condition 4
Here as we know that condition 2 will be applied on result data given by condition 1, condition 3 will be applied on on result data given by condition 2 and 1 and similarly condition 4 will be applied...
I want query which will execute further if any condition in between fails.
Means if **condition 3** will give no result (or null result set) then my **condition 4** will be applied on null result set so defiantly final output will be null, but I want if **condition 3** will give no result (or null result set) then **condition 4** "Should be Applied" to result set return by **condition 2 and 1**.
Here I can not change sequence of conditions due to performance issue.
Please guide me with query.
|
I got one simple solution for this and it is working in my scenario. Also I am able to reduce time for query execution on my big data. Defiantly two queries will be executed but i find this proper solution.
I used simple Union query.
**select c1, c2, c3, c4, c5 from table1 where c1 =0** //Condition 1
**AND c2="abc"** //Condition 2
**AND c3="xxx"** //Condition 3
**AND c4 = 5** //Condition 4
**UNION**
**select c1, c2, c3, c4, c5 from table1 where c1 =0** //Condition 1
**AND c2="abc"** //Condition 2
**AND c4 = 5** //Condition 4
If someone else has more accurate and proper solution. Please post it.
|
As far as I can see you want to have **condition 3** optional. That can be done, but would hardly be an efficient solution:
```
Select c1, c2, c3, c4, c5
From table1
Where c1 = 0
AND c2 = "abc"
AND (c3 = "xxx"
OR NOT Exists (Select '*' From table1 Where c1 = 0 AND c2 = "abc" AND c3 = "xxx")
)
AND c4 = 5
```
Better approach might be to use temporary table filtered on conditions 1 and 2 with further logic applied to this data subset.
|
output with condition based sub query in mysql
|
[
"",
"mysql",
"sql",
"subquery",
"conditional-statements",
"inner-query",
""
] |
While editing some queries to add alternatives for columns without values, I accidentally wrote something like this (here is the simplyfied version):
```
SELECT id, (SELECT name) FROM t
```
To my surprise, MySQL didn't throw any error, but completed the query giving my expected results (the `name` column values).
I tried to find any documentation about it, but with no success.
Is this SQL standard or a MySQL specialty?
Can I be sure that the result of this syntax is really the column value from the same (outer) table? The extended version would be like this:
```
SELECT id, (SELECT name FROM t AS t1 where t1.id=t2.id) FROM t AS t2
```
but the `EXPLAIN` reports `No tables used` in the `Extra` column for the former version, which I think is very nice.
Here's a simple [fiddle on SqlFiddle](http://sqlfiddle.com/#!6/cf948/3) (it keeps timing out for me, I hope you have better luck).
*Clarification: I know about subqueries, but I always wrote subqueries (correlated or not) that implied a table to select from, hence causing an additional step in the execution plan; my question is about this syntax and the result it gives, that in MySQL seems to return the expected value without any.*
|
This is the default behavior for the SQL language and it is defined on the [SQL ANSI 2011 over ISO/IEC 9075-1:2011(en)](https://www.iso.org/obp/ui/#iso:std:iso-iec:9075:-1:ed-4:v1:en) documentation. Unfortunately it is not open. This behavior is described on the section 4.11 SQL-Statements.
This behavior happens because the databases process the select comand without the from clause, therefore if it encounters:
```
select id, (select name) from some
```
It will try to find that `name` field as a column of the outer queries to process.
Fortunately I remember that some while ago I've [answered](https://stackoverflow.com/questions/20479135/oracle-as-keyword-and-subqueries/20479233#20479233) someone here and find a valid available link to an SQL ANSI document that is online in FULL but it is for the SQL ANSI 99 and the section may not be the same one as the new document. I think, did not check, that it is around the section 4.30. Take a look. And I really recommend the reading (I did that back in the day).
[Database Language SQL - ISO/IEC 9075-2:1999 (E)](http://web.cecs.pdx.edu/~len/sql1999.pdf)
|
What you within your first query is a correlated subquery which simply returns the **name** column from the table **t**. no actual subquery needs to run here (which is what your EXPLAIN is telling you).
> In a SQL database query, a correlated subquery (also known as a
> synchronized subquery) is a subquery (a query nested inside another
> query) that uses values from the outer query.
>
> <https://en.wikipedia.org/wiki/Correlated_subquery>
```
SELECT id, (SELECT name) FROM t
```
is the same as
```
SELECT id, (SELECT t.name) FROM t
```
---
Your 2nd query
```
SELECT id, (SELECT name FROM t AS t1 where t1.id=t2.id) FROM t AS t2
```
Also contains correlated subquery but this one is actually running a query on table t to find records where t1.id = t2.id.
|
Sql syntax: select without from clause as subquery in select (subselect)
|
[
"",
"mysql",
"sql",
"mysql-5.6",
""
] |
I have a table of messages that contains a message id field, a language id field and a text field.
An app needs to display a message based on the id and language which together form the unique key. All messages exist for language `EN`, but not all have been translated to other languages. So for English there will always be one record selected. But if the user is French and the app needs to display message #17 and it doesn't exist yet for French, I want to return message #17 in `EN`. I would like to accomplish this in one `SELECT` query, preferably with no `IF` Statements.
EDIT: based on the answers submitted - need to clarify that every message is translated to about 10 languages, maybe more. there *should* always be *exactly* *one* row returned based on the message id and the lang id. but if that row doesnt exist, the english message should be returned.
The final code:
`declare @msgid int=2, @langid varchar(2)='fr'
SELECT isnull(xx.msg, en.msg) msgtext
FROM appmessages en
LEFT JOIN appmessages xx ON en.msgid = xx.msgid and xx.langid=@langid
WHERE en.langid = 'en' and en.msgid=@msgid`
|
You can use a `LEFT JOIN` and `ISNULL` to achieve this
```
SELECT
ISNULL(fr.message, en.message) AS message
FROM message_table en
LEFT JOIN message_table fr ON
fr.message_id = en.message_id
AND fr.language = 'French'
WHERE
en.message_id = 17
AND en.language = 'English'
```
|
A simple approach just uses `order by` for prioritization:
```
select top 1 mt.*
from message_table mt
where mt.message_id = 17 and mt.language in ('French', 'English')
order by (case when mt.language = 'French' then 1 else 2 end);
```
For a single message, performance is optimized with an index on `message_table(message_id, language)`. The `order by` on two rows is trivial, so it should be very fast.
This approach also has the nice characteristic that it works even when some messages do not have English translations. It is also pretty simple to add additional languages, and the effect on processing time should be minimal.
For multiple messages, you can do something similar with window functions, but that would be a different question.
|
SQL Server: how to return 1 row as default if condition not met
|
[
"",
"sql",
"sql-server",
"database",
""
] |
Can someone help me to figure out how is the best way to do this?
I have a list of people with cars. I need to execute a query that will return people that have a type of car and don't have another type at the same time.
Here is my example:
```
ID Name CarType
----------- ---------- ----------
1 John MINI VAN
1 John SUV
2 Mary SUV
2 Mary SEDAN
3 Paul SPORT
3 Paul TRUCK
4 Joe SUV
4 Joe MINI VAN
```
For instance, I want to display only people that have SUV AND DON'T have MINI VAN. If we try the clause CarType IN ('SUV') AND NOT IN ('MINI VAN'), this will not work, because the second statement is just ignored.
In order to return people that have a type but don't have another type at the same time, I tried the following:
* Create a temporary table with the IN clause, let's say @Contains
* Create a temporary table with the NOT IN clause, let's say @DoesNotContain
* Join table with @Contains, this will do the IN clause
* On the where clause, look for IDs that are not in @DoesNotContain table.
The query that I am using is this:
```
--This is the IN Clause
declare @Contains table(
ID int not null
)
--This is the NOT IN Clause
declare @DoesNotContains table(
ID int not null
)
--Select IN
insert into @Contains
SELECT ID from @temp where CarType = 'SUV'
--Select NOT IN
insert into @DoesNotContains
SELECT ID from @temp where CarType = 'MINI VAN'
SELECT
a.ID, Name
FROM
@temp a
INNER JOIN @Contains b on b.ID = a.ID
WHERE
a.ID NOT IN (SELECT ID FROM @DoesNotContains)
Group by
a.ID, Name
```
This will return Mary because she has a SUV but does not have a MINI VAN.
Here are my questions:
* Is it possible to execute this IN and NOT IN in the query, without temp tables? Is there something new in SQL that does that? (Sorry, last time I worked with SQL was SQL 2005)
* Should we use temp tables for this?
* If this is the way to go, should I use IN and NOT IN instead of the JOIN?
* How to replace the NOT IN clause with a JOIN?
Thank y'all!
**EDIT**
I just tested the solutions but unfortunately I did not specify that I need a combination of cartypes. My bad :(
For instance, if I want all users that have SUV and MINI VAN but not TRUCK AND NOT SEDAN. In this case it only John is returned.
|
Here's one way
```
SELECT Id, Name
FROM Cars
WHERE CarType = 'SUV'
EXCEPT
SELECT Id, Name
FROM Cars
WHERE CarType = 'MINI VAN'
```
Or another
```
SELECT Id, Name
FROM Cars
WHERE CarType IN ('SUV', 'MINI VAN')
GROUP BY Id, Name
HAVING MIN(CarType) = 'SUV'
```
Or a more generic version that addresses the different requirement in the comment.
```
SELECT Id,
NAME
FROM Cars
WHERE CarType IN ( 'SUV', 'MINI VAN', 'TRUCK')
GROUP BY Id,
NAME
HAVING COUNT(DISTINCT CASE
WHEN CarType IN ( 'SUV', 'MINI VAN' ) THEN CarType
END) = 2
AND COUNT(DISTINCT CASE
WHEN CarType IN ( 'TRUCK' ) THEN CarType
END) = 0
```
|
This is normally accomplished with a single query in standard SQL, using `NOT EXISTS`:
```
SELECT *
FROM mytable AS t1
WHERE CarType = 'SUV' AND
NOT EXISTS (SELECT *
FROM mytable AS t2
WHERE t1.Name = t2.Name AND t2.CarType = 'MINI VAN')
```
The above query will select all people having `CarType = 'SUV'`, but do not have `CarType = 'MINI VAN'`.
|
How to have IN and NOT IN at same time
|
[
"",
"sql",
"sql-server",
""
] |
I am building a report based on the results of some SQL. There is an event that has 3 judges scoring. I am running into an issue with a specific fight in the night (The event is a fight). Here is my code:
```
USE DatabaseName;
DECLARE @EventID INT = ;
DECLARE @FightID INT = ;
----Judge 1
SELECT DISTINCT
JudgeNames.FirstName + ' ' + JudgeNames.LastName AS [Judge Name] ,
JudgeNames.PersonID ,
Event.EventID ,
Fights.FightID ,
FightScores.RoundNumber ,
FightScores.Contestant_1_PointsByRound ,
FightScores.Contestant_1_PointsDeducted ,
FightScores.Contestant_2_PointsByRound ,
FightScores.Contestant_2_PointsDeducted
INTO #Judge1
FROM dbo.tblEvents Event
INNER JOIN dbo.tblFights Fights ON Event.EventID = Fights.EventID
INNER JOIN dbo.tblFightJudge FightJudge ON FightJudge.fightid = Fights.FightID
INNER JOIN dbo.tblPersons JudgeNames ON JudgeNames.PersonID = FightJudge.judge1id
INNER JOIN dbo.tblEventJudge EJ ON EJ.EventID = Event.EventID
AND EJ.Judge_PersonID = JudgeNames.PersonID
INNER JOIN dbo.tblFightRoundScore FightScores ON Fights.FightID = FightScores.FightID
AND FightScores.EventJudgeID = EJ.EventJudgeID
WHERE Event.EventID = @EventID
AND Fights.FightID = @FightID;
----Judge 2
SELECT DISTINCT
JudgeNames.FirstName + ' ' + JudgeNames.LastName AS [Judge Name] ,
JudgeNames.PersonID ,
Event.EventID ,
Fights.FightID ,
FightScores.RoundNumber ,
FightScores.Contestant_1_PointsByRound ,
FightScores.Contestant_1_PointsDeducted ,
FightScores.Contestant_2_PointsByRound ,
FightScores.Contestant_2_PointsDeducted
INTO #Judge2
FROM dbo.tblEvents Event
INNER JOIN dbo.tblFights Fights ON Event.EventID = Fights.EventID
INNER JOIN dbo.tblFightJudge FightJudge ON FightJudge.fightid = Fights.FightID
INNER JOIN dbo.tblPersons JudgeNames ON JudgeNames.PersonID = FightJudge.judge2id
INNER JOIN dbo.tblEventJudge EJ ON EJ.EventID = Event.EventID
AND EJ.Judge_PersonID = JudgeNames.PersonID
INNER JOIN dbo.tblFightRoundScore FightScores ON Fights.FightID = FightScores.FightID
AND FightScores.EventJudgeID = EJ.EventJudgeID
WHERE Event.EventID = @EventID
AND Fights.FightID = @FightID;
----Judge 3
SELECT DISTINCT
JudgeNames.FirstName + ' ' + JudgeNames.LastName AS [Judge Name] ,
JudgeNames.PersonID ,
Event.EventID ,
Fights.FightID ,
FightScores.RoundNumber ,
FightScores.Contestant_1_PointsByRound ,
FightScores.Contestant_1_PointsDeducted ,
FightScores.Contestant_2_PointsByRound ,
FightScores.Contestant_2_PointsDeducted
INTO #Judge3
FROM dbo.tblEvents Event
INNER JOIN dbo.tblFights Fights ON Event.EventID = Fights.EventID
INNER JOIN dbo.tblFightJudge FightJudge ON FightJudge.fightid = Fights.FightID
INNER JOIN dbo.tblPersons JudgeNames ON JudgeNames.PersonID = FightJudge.judge3id
INNER JOIN dbo.tblEventJudge EJ ON EJ.EventID = Event.EventID
AND EJ.Judge_PersonID = JudgeNames.PersonID
INNER JOIN dbo.tblFightRoundScore FightScores ON Fights.FightID = FightScores.FightID
AND FightScores.EventJudgeID = EJ.EventJudgeID
WHERE Event.EventID = @EventID
AND Fights.FightID = @FightID;
----Fight Info
SELECT DISTINCT
Ref.FirstName + ' ' + Ref.LastName AS [Ref Name] ,
Fights.EventID ,
Fights.FightID ,
Fights.Rounds ,
Fights.ContestantID_1 ,
Fights.ContestantID_2 ,
C1.FirstName + ' ' + C1.LastName AS Fighter1 ,
C2.FirstName + ' ' + C2.LastName AS Fighter2 ,
Fights.Contestant1CornerColor AS Contestant1CornerColorHEX ,
Fights.Contestant2CornerColor AS Contestant2CornerColorHEX ,
Events.EventDate ,
Fights.Fight_WeightClass ,
Fights.FightNumber ,
( SELECT COUNT(FightNumber)
FROM dbo.tblFights
WHERE EventID = Fights.EventID
) AS NumOfFights
INTO #FightInfo
FROM dbo.tblFights Fights
INNER JOIN dbo.tblPersons Ref ON Fights.Referee_PersonID = Ref.PersonID
INNER JOIN dbo.tblEvents Events ON Fights.EventID = Events.EventID
INNER JOIN dbo.tblPersons C1 ON C1.PersonID = Fights.ContestantID_1
INNER JOIN dbo.tblPersons C2 ON C2.PersonID = Fights.ContestantID_2
WHERE Fights.EventID = @EventID
AND Fights.FightID = @FightID;
--MainQuery
SELECT DISTINCT
FI.EventID ,
FI.FightID ,
FI.FightNumber ,
FI.NumOfFights ,
FI.Rounds ,
FI.EventDate ,
FI.[Ref Name] ,
FI.Fight_WeightClass ,
FI.Contestant1CornerColorHEX ,
FI.Contestant2CornerColorHEX ,
FI.Fighter1 ,
FI.Fighter2 ,
#Judge1.[Judge Name] AS Judge1 ,
#Judge2.[Judge Name] AS Judge2 ,
#Judge3.[Judge Name] AS Judge3 ,
ISNULL(#Judge1.RoundNumber, 1) AS RoundNumber ,
--Judge 1
#Judge1.Contestant_1_PointsByRound AS J1C1Points ,
#Judge1.Contestant_1_PointsDeducted AS J1C1Deduct ,
( #Judge1.Contestant_1_PointsByRound
- #Judge1.Contestant_1_PointsDeducted ) AS J1C1Total ,
#Judge1.Contestant_2_PointsByRound AS J1C2Points ,
#Judge1.Contestant_2_PointsDeducted AS J1C2Deduct ,
( #Judge1.Contestant_2_PointsByRound
- #Judge1.Contestant_2_PointsDeducted ) AS J1C2Total ,
--Judge 2
#Judge2.Contestant_1_PointsByRound AS J2C1Points ,
#Judge2.Contestant_1_PointsDeducted AS J2C1Deduct ,
( #Judge2.Contestant_1_PointsByRound
- #Judge2.Contestant_1_PointsDeducted ) AS J2C1Total ,
#Judge2.Contestant_2_PointsByRound AS J2C2Points ,
#Judge2.Contestant_2_PointsDeducted AS J2C2Deduct ,
( #Judge2.Contestant_2_PointsByRound
- #Judge2.Contestant_2_PointsDeducted ) AS J2C2Total ,
--Judge3
#Judge3.Contestant_1_PointsByRound AS J3C1Points ,
#Judge3.Contestant_1_PointsDeducted AS J3C1Deduct ,
( #Judge3.Contestant_1_PointsByRound
- #Judge3.Contestant_1_PointsDeducted ) AS J3C1Total ,
#Judge3.Contestant_2_PointsByRound AS J3C2Points ,
#Judge3.Contestant_2_PointsDeducted AS J3C2Deduct ,
( #Judge3.Contestant_2_PointsByRound
- #Judge3.Contestant_2_PointsDeducted ) AS J3C2Total
INTO #MQ1
FROM #FightInfo FI
INNER JOIN #Judge1 ON #Judge1.FightID = FI.FightID
INNER JOIN #Judge2 ON #Judge2.FightID = FI.FightID
INNER JOIN #Judge3 ON #Judge3.FightID = FI.FightID
WHERE FI.FightID = @FightID
AND FI.EventID = @EventID
ORDER BY FI.FightNumber;
SELECT *
FROM #Judge1;
SELECT *
FROM #Judge2;
SELECT *
FROM #Judge3;
SELECT *
FROM #FightInfo;
SELECT *
FROM #MQ1;
DROP TABLE #FightInfo,#Judge1,#Judge2,#Judge3,#MQ1;
```
Each of the 3 judges returns 3 rounds of scores as follows:
[](https://i.stack.imgur.com/1T2Pr.jpg)
The "FightInfo" Query returns a single row as expected like:
[](https://i.stack.imgur.com/1Fdum.jpg)
The Problem comes when I run the final query. Judge 3 is returning 2 sets of points for each round. This is causing me to have 6 rows of data like this:
[](https://i.stack.imgur.com/3SgwK.jpg)
I apologize for the last picture being so small, but as you can see there are 6 rows returned. It is caused by Judge 3 having different "PointsByRound" numbers though I can't seem to see why or where that is being caused. Can someone provide some assistance to help me see?
|
On your joins for the #MQ1 table add RoundNumber.
This issue is if you join just on fightid if you get 27 rows. Because the fightids match all rows.
```
INNER JOIN #Judge1 ON #Judge1.FightID = FI.FightID
INNER JOIN #Judge2 ON #Judge2.FightID = FI.FightID AND #Judge2.RoundNumber = #Judge1.RoundNumber
INNER JOIN #Judge3 ON #Judge3.FightID = FI.FightID AND #Judge3.RoundNumber = #Judge1.RoundNumber
```
|
Exclude some of the columns you return in the distinct clause for testing.
This way you might discover that the problem is in columns that use computation.
|
Can't figure out why SQL is returning more rows than expected
|
[
"",
"sql",
"sql-server",
""
] |
I want to find all lines of data that have a value, say 'N/A'
I want to then update ALL the lines of data where they have the same CommonID into the NewDataHere Column so in the example below ID 1 and 2 would be affected
I am doing this in a stored procedure
**Code for far:**
```
DECLARE @sqlPRatingChange NVARCHAR(MAX)
SET @sqlPRatingChange = 'UPDATE TblAsbestos SET NewDataHere= ''NA''
WHERE (SELECT ID FROM TBLASBESTOS WHERE VALUE= ''N/A'')'''
EXEC (@sqlPRatingChange)
```
**Example of Database as it should look after code**
* ID-VALUE-NewDataHere
1-N/A-N/A
2-C-N/A
2-N/A-N/A
1-A-N/A
3-B-''
|
Why are you using dynamic SQL? Your query seems close enough. It just needs a correlation clause:
```
UPDATE TblAsbestos
SET NewDataHere = 'NA'
WHERE (SELECT ID FROM TBLASBESTOS a2 WHERE VALUE = 'N/A' AND TblAsbestos.id = a2.id);
```
In SQL Server, I might be inclined to do this using a CTE and window functions:
```
with toupdate as (
select a.*,
sum(case when value = 'N/A' then 1 else 0 end) over (partition by id) as numNAs
from TblAsbestos a
)
update toupdate
set NewDataHere = 'NA'
where numNAs > 0;
```
|
This should possibly be a comment on Gordon's answer, but it got too long and the formatting that an answer affords helps...
The incorrect syntax error is because in SQL Server you cannot alias the target of an update statement (not to be confused with using an alias as the target which is allowed). The where clause is also incorrect, it appears to be mix between an `EXISTS` clause and an `IN` clause, but has ended up as neither. I think you need:
```
UPDATE TblAsbestos
SET NewDataHere = 'NA'
WHERE EXISTS
( SELECT 1
FROM TblAsbestos AS a
WHERE a.Value = 'N/A'
AND a.id = TblAsbestos.id
);
```
Or
```
UPDATE TblAsbestos
SET NewDataHere = 'NA'
WHERE ID IN (SELECT a.ID FROM TblAsbestos AS a WHERE a.Value = 'N/A');
```
|
Update Multiple ID's based on field value
|
[
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
sql update depending on the current value. a table(id,color,code) value for code are (a,b,c,...) How can i change all a to AA and c to CC without accessing a record more than once.
I think its like getting code for each color and if a -> AA and if c -> CC
|
Use `Case statement`
```
update yourtable
set code = case code when 'a' then 'AA'
when 'c' then 'CC'
END
Where code in('a','c')
```
|
Here is an amusing alternative:
```
update t
set code = upper(code) || upper(code)
where code in ('a', 'c');
```
|
update by accessing record only once.
|
[
"",
"sql",
"oracle",
""
] |
This is very simple but somehow I'm doing something wrong with this query on my database.
I have this query below:
```
SELECT login FROM accounts WHERE login = "loginname";
```
When I execute this query the result I get is this:
```
column "loginname" does not exist
```
This is a no brainer, why is this query not working properly? I have a login column and I know that this user exists because I've found this person with the rails console. Why is the login criteria referring to itself as a column?
|
Try with single quotes `''` if you are trying to match a string
```
SELECT login FROM accounts WHERE login = 'loginname';
```
Check the [documentation](http://www.postgresql.org/docs/current/static/sql-syntax-lexical.html#SQL-SYNTAX-CONSTANTS)
> There is a second kind of identifier: the delimited identifier or
> quoted identifier. It is formed by enclosing an arbitrary sequence of
> characters in double-quotes ("). A delimited identifier is always an
> identifier, never a key word. **So "select" could be used to refer to a
> column or table named "select"**, whereas an unquoted select would be
> taken as a key word and would therefore provoke a parse error when
> used where a table or column name is expected.
|
Double quotes (`"`) are used to refer to object names, in a case sensitive way. In this case, `"loginname"` is interpreted as a column name, and the query fails, since there is no such column. In order to refer to a string literal, you should use single quotes (`'`):
```
SELECT login FROM accounts WHERE login = 'loginname';
-- Here ---------------------------------^---------^
```
|
Can someone help point out to me what is wrong with this no brainer WHERE clause?
|
[
"",
"sql",
"postgresql",
"select",
"syntax-error",
""
] |
I have a program that is linked to a sql DB, with 2 tables - `Customers` and `SInfo`.
Customers has the normal columns:
```
CUSTOMERID (Primary Key)
FIRSTNAME
LASTNAME
EMAIL
```
SInfo has details about the Customer:
```
SSheetID (Primary Key)
CustomerID
SerialNumber
```
When I use the query builder in .net, I use an `inner join` to combine the tables, and use a filter to search for a serial number, but I am getting an error when the primary key is shown more than once.
[](https://i.stack.imgur.com/i77Hh.jpg)
I tried to use `distinct`, but if one field was different, I would get the error, and `GROUP BY` is killing me.
So my question is, what would be the best practice if a Customer (CustomerID) has the same Serial Number more than once, but I just want to show that CustomerID once, but still fill out FirstName, LastName, Email?
Any help is appreciated.
|
Various options...
via `distinct`:
```
select distinct c.* -- or better: more specific c. columns
from SInfo s
inner join Customers c on c.CUSTOMERID = s.CustomerID
where s.SerialNumber = @serial
```
via `exists`:
```
select *
from Customers c
where exists (
select 1 from SInfo s
where s.CustomerID = c.CUSTOMERID
and s.SerialNumber = @serial)
```
but as noted in the comments: a unique constraint over `SInfo.SerialNumber`, or perhaps spanning `SInfo.SerialNumber and SInfo.CustomerID` - probably makes sense.
|
You can use natural join for this case because when you use natural join, it will match people with the same Customer ID and then use GROUP BY so it will show the name one time.
```
select first_name, last_name, email
from customer natural join Sinfo
group by customerID, first_name, last_name, email
```
|
SQL Group By, Distinct confusion
|
[
"",
"sql",
".net",
""
] |
I am using the below query to get total amount after a discount.
My issue is when the discount is equal to zero, the total amount becomes zero.
How can I resolve this issue?
```
SELECT
CAST(SUM(Quantity * UnitPrice * (Discount / 100)) AS varchar(50))
FROM
Stock_Purchase_Details
```
|
simple case construct
```
unitPrice *
case when discount > 0 then (discount / 100)
else 1 end
```
That's for the code you posted. Normally, a discounted price is
```
unitPrice * ((100 - discount) / 100)
```
|
If you want final amount after discount, you should use
```
CAST(SUM(Quantity * UnitPrice * (1-(Discount/100)) AS VARCHAR(50))
```
This will give you the amount after discount. Your current formula gives you the amount discounted, not the amount after discount
|
SQL query issue with zero discount
|
[
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
SQL amateur here.
I have a table containing voucher codes:
```
id voucherCode UserId
------------------------
1 abcde 13
2 bcdef 11
3 cdefg
4 defgh
```
Now if one of my users qualify for a voucher code, I get one from my table:
```
SELECT TOP 1 * FROM tableName WHERE UserId IS NULL;
UPDATE tableName SET UserId = @UserID WHERE id = @SelectedIdFromAboveSelect;
```
I have to be sure that each row is only selected **once**. If multiple users need a voucher code, there is a small time gap between the `SELECT` and the `UPDATE`. If then a second `SELECT` is executed, it may `SELECT` the same row a second time. How do I prevent that?
|
I guess you can do it in opposite order; I mean, you `UPDATE` the table with the user ID and then `SELECT` the voucherCode. This way you shouldn't have any problem.
|
You can do this by returning the value in the `update` statement, using the `output` clause:
```
declare @ids table (userid int);
with toupdate as (
SELECT TOP 1 *
FROM tableName
WHERE UserId IS NULL
)
UPDATE toupdate
SET UserId = @UserId
OUTPUT inserted.UserId INTO @ids;
```
|
How to lock a row so that a select returns a row exactly once?
|
[
"",
"sql",
"sql-server",
"database",
"t-sql",
"sql-server-2014",
""
] |
I want to find age, for example, between 20 to 30 from my table from the current system date.
Below is my table details:
```
GivenName DOB
Raj 1950-06-06 00:00:00.000
Rahul 1951-01-06 00:00:00.000
Mohan 1952-11-09 00:00:00.000
khan 1953-07-24 00:00:00.000
```
|
> for example, between 20 to 30
Use [`DATEDIFF`](https://msdn.microsoft.com/en-us/library/ms189794(v=sql.120).aspx):
```
SELECT Age = DATEDIFF(year, DOB, GetDate()),
Between20_30 = CASE WHEN DATEDIFF(year, DOB, GetDate()) BETWEEN 20 AND 30
Then 'yes' ELSE 'no' END
FROM dbo.Table1
```
[**Demo**](http://sqlfiddle.com/#!6/98134/2/0)
If you want to filter by persons who are between 20 and 30 use a `WHERE` clause:
```
WHERE DATEDIFF(year, DOB, GetDate()) BETWEEN 20 AND 30
```
---
Since `DATEDIFF` ist not precise(treats the month difference between 12/31 and 01/01 as one month), if that's an issue you could use [this](https://stackoverflow.com/a/57720/284240) approach.
|
```
select GivenName,Age = DATEDIFF(year, DOB, GetDate())
FROM [dbo].[AgeCalc] where DATEDIFF(year, DOB, GetDate()) BETWEEN 20 AND 30
```
|
SQL Select query using current date time to get the users ages?
|
[
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I'm having beginner troubles with MySQL. I'm trying to build a DB of parts which have a ten digit alphanumeric part number based on the department and class of a part. For example, a part from department "Foo" of class "Bar" might be *FOBAR10000*. The departments and classes are stored in their own tables, so I store the IDs with the part instead of the strings "FO" and "BAR" in the parts table.
I've come up with a MySQL query to lookup and concatenate the full part name.
```
SELECT pl.idPartsList as 'resultid', concat(pd.DeptShortName, pc.ClassShortName,pl.PartIntID) as 'Fullname'
FROM partdepartments pd, partclasses pc, partslist pl
WHERE pl.PartDeptId = pd.idPartDepartments and pl.PartClassID = pc.idPartClasses;
```
Which generates:
```
resultid | Fullname
---------------------
1 | FOBAR10000
```
I want to assign this result back to the part under the column PartFullAlphaID, as follows, to avoid having to run this query often.
Before:
```
idPartslist | PartDeptID | PartClassID | PartIntID | PartFullAlphaID
---------------------------------------------------------------------
1 | 1 | 1 | 10000 |
```
After:
```
idPartslist | PartDeptID | PartClassID | PartIntID | PartFullAlphaID
---------------------------------------------------------------------
1 | 1 | 1 | 10000 | FOBAR10000
```
but the following doesn't work:
```
UPDATE test_db_1.partslist
SET PartFullAlphaID = Fullname
WHERE test_db_1.partslist.idPartsList = resultid;
```
Because: *Error Code: 1054. Unknown column 'resultid' in 'where clause'*
How can I assign this string value back to the part?
|
This is an update on joined tables.
Try this Query:
```
UPDATE partslist pl
JOIN partdepartments pd ON pl.PartDeptId = pd.idPartDepartments
JOIN partclasses pc ON pl.PartClassID = pc.idPartClasses
SET pl.PartFullAlphaID = concat(pd.DeptShortName, pc.ClassShortName, pl.PartIntID)
```
also look at [stackoverflow.com/../how-to-use-join-in-update-query](https://stackoverflow.com/questions/15209414/how-to-use-join-in-update-query)
|
Have you tried selecting the results out into variables?
```
DECLARE @ResultID varchar(10),
@FullName varchar(100)
SELECT @ResultID = pl.idPartsList,
@FullName = concat(pd.DeptShortName, pc.ClassShortName,pl.PartIntID)
FROM partdepartments pd, partclasses pc, partslist pl
WHERE pl.PartDeptId = pd.idPartDepartments
AND pl.PartClassID = pc.idPartClasses;
UPDATE test_db_1.partslist
SET PartFullAlphaID = @FullName
WHERE test_db_1.partslist.idPartsList = @ResultID;
```
I use `MSSQL` so the syntax may be (very slightly) different, but I use this syntax often when updating records.
|
How do I assign this concatenated value back to its table?
|
[
"",
"mysql",
"sql",
"database",
""
] |
Is it accurate to say that of the existing graph query languages (Cypher, Datalog, Sparql etc) Gremlin is the only one that's Turing complete?
In case it matters, I'm not looking for edge cases like the Turing completeness proof of Magic: the Gathering; the intent of my question is whether Gremlin is the only graph query language that is suitable in practice for performing arbitrary computation on graphs.
|
I'm not sure about what you include in the `etc.`.
But I think your statement is correct. As you say that you are not looking for edge cases or exotic manipulation of the language.
1. [Cypher is not turing complete](https://www.quora.com/Should-I-learn-Cypher-or-Gremlin-for-operating-a-Neo4j-database)
2. [SQL is not properly t.c.](https://stackoverflow.com/a/900062/5973334)
3. [By any practical definition, SPARQL is not t.c.](https://link.springer.com/article/10.1007/s00224-014-9536-x)
4. [Datalog is not t.c.](https://en.wikipedia.org/wiki/Datalog#Features,_limitations_and_extensions)
5. [AQL is more or less as powerful as standard SQL](https://www.arangodb.com/why-arangodb/sql-aql-comparison/)
Yet, we should not look at turing completeness as a must-have feature. The power of declarative query languages is that the hard work is done by the system, while the user *just* describes what they are looking for. This has the added advantage that the system is able to find optimized plans to get to the right information.
|
* cypher is not Turing complete
* GSQL is Turing complete
* Gremlin is Turing complete.
See the detailed comparison of them at this white paper
<https://info.tigergraph.com/gsql>
|
Turing complete graph query languages
|
[
"",
"sql",
"gremlin",
"graph-traversal",
"datalog",
"turing-complete",
""
] |
Struggling with a create table statement which is based on this select into statement below:
```
@MaxAPDRefundAmount money = 13.00
...
select pkd.*, pd.ProviderReference, per.FirstName, per.Surname, @MaxAPDRefundAmount [MaxAPDRefundAmount],commission.Type [Commission] into #StagedData from CTE_PackageData pkd
inner join J2H.dbo.Package pk on pkd.Reference = pk.Reference
inner join J2H.dbo.Product pd on pk.PackageId = pd.PackageId
inner join J2H.dbo.FlightReservation fr on pd.ProductId = fr.ProductId
and fr.FlightBoundID = 1
inner join J2H.dbo.ProductPerson pp on pd.ProductId = pp.ProductID
and pp.StatusId < 7
inner join J2H.dbo.Flight f on fr.FlightId = f.FlightID
inner join J2H.dbo.Person per on pk.PackageId = per.PackageId
and per.PersonId = pp.PersonId
inner join J2H.dbo.PersonType pt on per.PersonTypeId = pt.PersonTypeID
```
We are changing a select into to just normal insert and select, so need a create table (we are going to create a temp (hash tag table) and not declaring a variable table. Also there is a pkd.\* at the start as well so I am confused in knowing which fields to include in the create table. Do I include all the fields in the select statement into the create statement?
Update:
So virtually I know I need to include the data types below but I can just do:
```
create table #StagedData
(
pkd.*,
pd.ProviderReference,
per.FirstName,
per.Surname,
@MaxAPDRefundAmount [MaxAPDRefundAmount],
commission
)
```
|
The documentation of the `CREATE TABLE` statement is pretty straightforward.
No. Clearly, you cannot use `pkd.*` in a `create table` statement.
What you can do is run your old `SELECT INTO` statement as a straight SELECT (remove the `INTO #stagedata`) part, and look at the columns that get returned by the SELECT.
Then write a `CREATE TABLE` statement that includes those columns.
|
"Do I include all the fields in the select statement into the create statement?" Well, that depends, if you need them, than yes, if not than no. It's impossible for us to say whether you need them... If you're running this exact query as `insert`, than yes.
As for the create statement, you can run the query you have, but replace `into #StagedData` with something like `into TEMP_StagedData`. In management studio you can let sql server build the create query for you: right-click the newly created `TEMP_StagedData` table in the object explorer (remember to refresh), `script Table as`, `CREATE To` and select `New Query Editor Window`.
|
How to create a table with multiple columns
|
[
"",
"sql",
"sql-server",
""
] |
I want to insert `table1.id` into `table2.t1col` only if `table1.id` doesn't exist in `table2.t1col`, yet.
I think I have to use :
```
insert into table2 name (t1col) value (select id from table1)
```
but I want to add only if that `id` doesn't exist in `table2` already.
|
A unique/index constraint guarantees the uniqueness of values. So, it is recommended.
Unfortunately, though, a constraint violation causes the entire `insert` to fail. So, you can do:
```
insert into table2(t1col)
select id
from table1 t1
where not exists (select 1 from table2 t2 where t2.t1col = t1.id);
```
You should also have a unique index/constraint to prevent problems in the future.
|
You can use a Unique Index for preventing duplicated rows.
But if you want to insert rows filtering it to not insert duplicated rows, you can do this.
```
INSERT INTO table2 (idcol)
SELECT id FROM table1
EXCEPT
SELECT idcol FROM table2;
```
|
INSERT into a table from SELECT only if value doesn't exist
|
[
"",
"sql",
"postgresql",
"sql-insert",
"upsert",
""
] |
I would like to sort (the result of the sub select) by 3 columns (Priority, ExpectedDate, CreateDate) but for a few row sort should work in different way.
It is hard to describe in words so I prepared a picture:
[](https://i.stack.imgur.com/Uz4JN.png)
Column **Rank** in **Before** table is right now:
```
ROW_NUMBER() OVER(ORDER BY Priority DESC, ExpectedDate DESC, CreateDate ASC) AS [Rank],
```
As you can see **ShouldBeAfter** column indicates the **ID**, after which this row should always appear, regardless of the sort.
How to write a query in order to achieve a state of **After**?
**EDIT 1:**
Sample data:
```
DECLARE @Queue TABLE
(
[ChildID] INT,
[ParentID] INT,
[No] INT,
[Change] INT,
[Priority] INT,
[ExpectedDate] DATETIME,
[CreateDate] DATETIME
)
INSERT INTO @Queue VALUES (242, 0, 0, 0, 3, '1900-01-01 00:00:00.000', '2015-11-27 15:08:40.677')
INSERT INTO @Queue VALUES (243, 274, 0, 0, 3, '1900-01-01 00:00:00.000', '2015-11-27 15:22:46.350')
INSERT INTO @Queue VALUES (244, 0, 0, 0, 3, '1900-01-01 00:00:00.000', '2015-11-27 15:29:52.010')
INSERT INTO @Queue VALUES (259, 0, 0, 0, 3, '1900-01-01 00:00:00.000', '2015-11-30 15:54:48.710')
INSERT INTO @Queue VALUES (261, 0, 0, 0, 4, '1900-01-01 00:00:00.000', '2015-12-01 11:07:32.357')
INSERT INTO @Queue VALUES (263, 0, 0, 0, 5, '1900-01-01 00:00:00.000', '2015-12-02 12:07:01.980')
INSERT INTO @Queue VALUES (264, 0, 0, 0, 2, '1900-01-01 00:00:00.000', '2015-12-03 14:58:19.717')
INSERT INTO @Queue VALUES (266, 0, 0, 0, 3, '1900-01-01 00:00:00.000', '2015-12-08 09:55:06.277')
INSERT INTO @Queue VALUES (269, 0, 0, 0, 3, '2015-12-16 00:00:00.000', '2015-12-08 17:53:24.820')
INSERT INTO @Queue VALUES (270, 0, 0, 0, 3, '1900-01-01 00:00:00.000', '2015-12-09 15:50:37.970')
INSERT INTO @Queue VALUES (272, 0, 0, 0, 3, '1900-01-01 00:00:00.000', '2015-12-11 12:06:19.253')
INSERT INTO @Queue VALUES (273, 242, 0, 0, 3, '1900-01-01 00:00:00.000', '2015-12-11 12:08:20.010')
INSERT INTO @Queue VALUES (274, 0, 0, 0, 2, '1900-01-01 00:00:00.000', '2015-12-11 12:09:00.200')
INSERT INTO @Queue VALUES (275, 0, 0, 0, 3, '1900-01-01 00:00:00.000', '2015-12-11 12:14:50.110')
INSERT INTO @Queue VALUES (276, 0, 0, 0, 3, '1900-01-01 00:00:00.000', '2015-12-11 12:17:49.220')
INSERT INTO @Queue VALUES (277, 0, 0, 0, 3, '1900-01-01 00:00:00.000', '2015-12-11 12:24:28.823')
INSERT INTO @Queue VALUES (278, 0, 0, 0, 5, '2015-12-10 00:00:00.000', '2015-12-11 12:27:53.803')
INSERT INTO @Queue VALUES (279, 0, 0, 0, 3, '1900-01-01 00:00:00.000', '2015-12-11 12:32:14.397')
INSERT INTO @Queue VALUES (280, 0, 0, 0, 2, '1900-01-01 00:00:00.000', '2015-12-11 13:56:06.080')
INSERT INTO @Queue VALUES (281, 0, 0, 0, 2, '1900-01-01 00:00:00.000', '2015-12-15 10:16:35.057')
INSERT INTO @Queue VALUES (282, 276, 0, 0, 3, '1900-01-01 00:00:00.000', '2015-12-15 10:18:50.180')
INSERT INTO @Queue VALUES (284, 0, 0, 0, 3, '1900-01-01 00:00:00.000', '2015-12-15 11:33:33.553')
```
|
You can do it in two-step process using CTEs:
```
;WITH InitialRank AS (
SELECT *,
ROW_NUMBER() OVER(ORDER BY Priority DESC,
ExpectedDate DESC,
CreateDate ASC) AS [Rank]
FROM Queue
), FinalRank AS (
SELECT t1.ID, t1.ShouldBeAfter, t1.No, t1.Change,
t1.Priority, t1.ExpectedDate, t1.CreateDate,
COALESCE(CAST(t2.Rank AS DECIMAL(4,1)) + 0.5, t1.Rank) AS Rank
FROM InitialRank AS t1
LEFT JOIN InitialRank AS t2
ON t1.ShouldBeAfter <> 0 AND t1.ShouldBeAfter = t2.ID
)
SELECT ID, ShouldBeAfter, No, Change,
Priority, ExpectedDate, CreateDate,
ROW_NUMBER() OVER (ORDER BY Rank) AS Rank
FROM FinalRank
ORDER BY Rank
```
* The first step calculates the *'initial'* rank as defined by the 3 columns `(Priority, ExpectedDate, CreateDate)`.
* Second step alters the rank of all rows having a non-zero `ShouldBeAfter` value associated with them: the new value of the rank is the rank of 'comes before' row plus `0.5`, so that the row will be ordered *right after* the 'comes before' row.
*Note*: The above will work as long as there are only *single-level* dependencies.
[**Demo here**](http://sqlfiddle.com/#!3/b0be8/7)
|
Another way to do the same without explicit join:
```
SELECT *,
MIN(CASE WHEN ShouldBeAfter = 0 THEN PreRank END)
OVER(PARTITION BY CASE WHEN ShouldBeAfter = 0 THEN ID ELSE ShouldBeAfter END) AS [Rank]
FROM (
SELECT *,
ROW_NUMBER() OVER(ORDER BY Priority DESC, ExpectedDate DESC, CreateDate ASC) AS [PreRank]
FROM Queue
)A
ORDER BY [Rank], ShouldBeAfter
```
[Demo here](http://sqlfiddle.com/#!3/b0be8/12/0)
|
SQL ORDER BY with exceptions
|
[
"",
"sql",
"sql-server-2008-r2",
"sql-order-by",
"rank",
""
] |
Here is my Query in SQL Server...
```
SELECT hs.NAME Highschooler,
hs.grade inGrade1,
hs2.NAME likes,
hs2.grade inGrade2
FROM highschooler hs
JOIN likes l ON hs.id = l.id1
JOIN highschooler hs2 ON hs2.id = l.id2
```
I get
```
HIGHSCHOOLER INGRADE1 LIKES INGRADE2
1-----Cassandra 9 Gabriel 9
2-----Gabriel 9 Cassandra 9
3-----Andrew 10 Cassandra 9
4-----John 12 Haley 10
5-----Brittany 10 Kris 10
6-----Alexis 11 Kris 10
7-----Gabriel 11 Alexis 11
8-----Kyle 12 Jessica 11
9-----Austin 11 Jordan 12
10----Jessica 11 Kyle 12
```
I want to remove the paired duplicates from the column HIGHSCHOOLER and LIKES...
like in the table above
the **8th** and **10th** rows have the same pair **(kyle - jessica)** and **(Jessica - kyle)** i.e duplicate pair and **i want to remove that duplicate**
This is the link of the question that i faced..
<https://lagunita.stanford.edu/courses/DB/SQL/SelfPaced/courseware/ch-sql/seq-exercise-sql_social_query_core/>
i think u should get registered to get the questions
and in the marked section and the marked question
[](https://i.stack.imgur.com/dFpaU.png)
[](https://i.stack.imgur.com/q7270.png)
and the link for the database
<https://lagunita.stanford.edu/c4x/DB/SQL/asset/socialdata.html>
|
You probably want to leave data, because Cassandra likes Gabriel and Gabriel likes Cassandra are different actions. So I will suggest the following query:
```
WITH cte AS(SELECT hs.NAME Highschooler ,
hs.grade inGrade1 ,
hs2.NAME likes ,
hs2.grade inGrade2 ,
ROW_NUMBER() OVER (PARTITION BY CASE WHEN l.id1 < l.id2 THEN l.id1
ELSE l.id2 END,
CASE WHEN l.id1 < l.id2 THEN l.id2
ELSE l.id1 END
ORDER BY (SELECT NULL)) rn
FROM highschooler hs
JOIN likes l ON hs.id = l.id1
JOIN highschooler hs2 ON hs2.id = l.id2)
SELECT * FROM cte WHERE rn = 1
```
This is the demostration:
```
DECLARE @t TABLE ( id1 INT, id2 INT )
INSERT INTO @t
VALUES ( 1, 2 ),
( 2, 1 ),
( 1, 3 ),
( 5, 6 ),
( 6, 5 ),
( 7, 8 );
WITH cte AS(SELECT * ,
ROW_NUMBER() OVER (PARTITION BY CASE WHEN id1 < id2 THEN id1
ELSE id2 END,
CASE WHEN id1 < id2 THEN id2
ELSE id1 END
ORDER BY (SELECT NULL)) rn
FROM @t)
SELECT * FROM cte WHERE rn = 1
```
Output:
```
id1 id2 rn
1 2 1
1 3 1
5 6 1
7 8 1
```
|
You need to remove the duplicates from `likes`. One method is to use `union all` (and this is probably the fastest method if you have an index on `likes(id1, id2)`). You can do the removal before doing the `join`:
```
SELECT hs.NAME as Highschooler, hs.grade as inGrade1, hs2.NAME as likes, hs2.grade as inGrade2
FROM (select l.id1, l.id2
from likes l
where l.id1 < l.id2
union all
select l.id1, l.id2
from likes l
where l.id1 > l.id2 and
not exists (select 1 from likes l2 where l.id2 = l2.id1 and l.id1 = l2.id2)
) l join
highschooler hs
ON hs.id = l.id1 JOIN
highschooler hs2
ON hs2.id = l.id2;
```
|
How do I remove duplicate rows based on two Columns? (E.g. A Pair Value Set)
|
[
"",
"sql",
"sql-server-2012",
""
] |
I have the following SQL Server 2000 query:
```
select distinct
m.[Index], m.part as [Part No]
from
Ctable c, MTable m
where
m.part *= c.part
```
Is the corresponding SQL Server 2012 query for it this?
```
select distinct
m.[Index], m.part as [Part No]
from
Ctable c
right join
MTable m on m.part = c.part
```
So basically Asterisk= is left join and =Asterisk is right join? I had to do right join on the above query since MTable is the right table on the 2012 query. Please advice.
|
First congrats on getting rid of those old joins, they were not even accurate in SQL server 2000 as they could be misinterpreted as cross joins. That may even be why the distinct was put in (or it could have something to with your data model, without understanding the data you have I can't tell).
I believe your conversion to the right join is correct, but check the results of both queries and make sure they are returning the same results. Then try removing the distinct and check those results to determine if it is still needed. If it was added to get rid of the possibility of cross joining, it may no longer be necessary and it is an expensive operation, so if it can be dispensed with, that is best.
|
non ANSI standard outer joins were deprecated in 2000 and de-supported in 2005. See <https://msdn.microsoft.com/en-us/library/ms144262(v=sql.90).aspx> Users could still change db\_compat level to get temporary relief for a while but the operators were completely removed in 2012 so you have no alternative.
Modify your queries to use ANSI standard outer joins, they'll work on current and legacy versions, including 2000.
|
SQL Server 2000 join query to SQL Server 2012
|
[
"",
"sql",
"sql-server",
"sql-server-2012",
"sql-server-2000",
""
] |
I am a beginner in SQL. I have two tables, one is student\_records and the other is a table student\_fees in which the records for students on discounted fees (fee\_type\_code=2) as well as those on regular fees (fee\_type\_code=1) exists. the code for fee type is fee\_type\_code. There is a mistake in system due to which some of the students are getting both fee types. I want to get all the error records. First, i have two queries that work fine separately but i am trying to merge them in one query and then create a join on temporary tables:
```
select
student_id, fee_type_code
from
((select * from student_records r, student_fees f
where s.student_id=f.student_id and fee_type_code=1) A
inner join
(select * from student_records r, student_fees f
where
s.student_id=f.student_id and fee_type_code=2) B
on A.student_id=B.student_id);
```
I apologize for any inconvinience in advance or if this is a question too naive, but i am getting stuck in this. The error i am getting is **"Reference to student\_id is ambiguous..."**
|
If your goal is to get a list of students that have both fee types then you can use `group by` and `having` instead:
```
select sr.student_id
from student_records sr
join student_fees sf on sr.student_id = sf.student_id
where sf.fee_type_code in (1,2)
group by sr.student_id
having count(distinct sf.fee_type_code) = 2
```
|
As others mentioned earlier, there a few syntactically simpler techniques you could employ to get to this dataset but I wanted to make sure you understood what was wrong with your original query.
To explain
> "Reference to student\_id is ambiguous..."
You have selected `student_id` and `fee_type_code` in your `SELECT` statement but you have actually referenced these fields twice in your subquery (once in subquery `A` and once in subquery `B`). The SQL engine is not intelligent enough to recognize that these represent a duplicate of the same data so it cannot decide which subquery field you want to see. To complete the query as you originally designed it, you will need to explicitly tell the SQL engine which fields you want to see in your `SELECT`:
```
select A.student_id, A.fee_type_code --This can be A or B fields as they represent the
-- same records but a table must be defined
from
((select student_id, fee_type_code
from student_records r, student_fees f
where s.student_id=f.student_id and fee_type_code=1) A
inner join
(select student_id, fee_type_code
from student_records r, student_fees f
where s.student_id=f.student_id and fee_type_code=2) B
on A.student_id=B.student_id);
```
|
sql join between two subqueries that are similar
|
[
"",
"sql",
"db2",
""
] |
I have a table tbl1
How can I split the column values by 10 (number of characters)
FROM:
```
Column1
Butuan City Philippines
Zamboanga City Philippines
Manila City Philippines
```
TO:
```
Column1 Column2
Butuan Cit y Philippines
Zamboanga City Philippines
Manila Cit y Philippines
```
|
You can use the `SUBSTRING()` function:
```
SELECT SUBSTRING(Column1, 1, 10) AS Column1,
SUBSTRING(Column1, 11, LEN(Column1) - 10) AS Column2
FROM yourtable
```
Note that we do not have to worry about using indices in substring which are greater than the length of `Column1`, q.v. the [documentation](https://msdn.microsoft.com/en-sg/library/ms187748.aspx) which states:
> If start [second parameter] is greater than the number of characters in the value expression, a zero-length expression is returned.
and
> If the sum of start and length is greater than the number of characters in expression, the whole value expression beginning at start is returned.
|
You can use the in-build [SUBSTRING()](https://msdn.microsoft.com/en-IN/library/ms187748.aspx) function of SQL to achieve your expected result.
For E.g.
```
IF (LEN(Column1) > 10)
BEGIN
SELECT SUBSTRING(Column1, 1, 10) AS Column1,SUBSTRING(Column1, 11, LEN(Column1) - 10) AS Column2
FROM <TABLE>
END
```
|
SQL: Split Column Values into two Columns
|
[
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I need to create an output where I got one row per year-month.
Assume the dataset is:
```
id | dateStart | dateEnd
1 | 2015-01-01 00:00:00.000 | 2015-03-31 00:00:00.000
2 | 2014-07-01 00:00:00.000 | 2014-08-31 00:00:00.000
...
```
I need the following output:
```
id | year-month
1 | 2015-01
1 | 2015-02
1 | 2015-03
2 | 2014-07
2 | 2014-08
```
The output can be any datatype since I can just change that later.
That is for 2015-01 the following is ok, "2015-01-01 00:00:00.000", "2015-01-01", "201501", "2015 | jan" ect.
Note I'm using SQL Server 2005.
|
Here is a method that uses recursive CTEs:
```
with CTE as (
select id, dateStart as dte, dateEnd
from t
union all
select id, dateadd(month, 1, dte), dateEnd
from CTE
where dateadd(month, 1, dte) < dateEnd
)
select id, dte
from CTE;
```
You can convert the final result into any format you like. For instance:
```
select id, year(dte) * 10000 + month(dte) as yyyymm_int
```
or
```
select id, cast(year(dte) * 10000 + month(dte) as varchar(255)) as yyyymm
```
|
Generate tally table(just make sure you get enough rows there). tally will contain values `0,1,2,.....n`. Then you do a join with condition adding thise values as months to `startDate` until it is greater then `endDate`:
```
DECLARE @t TABLE
(
id INT ,
dateStart DATETIME ,
dateEnd DATETIME
)
INSERT INTO @t
VALUES ( 1, '2015-01-01 00:00:00.000', '2015-03-31 00:00:00.000' ),
( 2, '2014-07-01 00:00:00.000', '2014-08-31 00:00:00.000' )
;WITH cte AS(SELECT -1 + ROW_NUMBER() OVER(ORDER BY t1.m) m
FROM(VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0))t1(m) CROSS JOIN
(VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0))t2(m))
SELECT t.id,
DATEADD(mm, c.m, t.dateStart) AS year_month
FROM cte c
JOIN @t t ON DATEADD(mm, c.m, t.dateStart) <= t.dateEnd
ORDER BY t.id, year_month
```
Output:
```
id year_month
1 2015-01-01 00:00:00.000
1 2015-02-01 00:00:00.000
1 2015-03-01 00:00:00.000
2 2014-07-01 00:00:00.000
2 2014-08-01 00:00:00.000
```
|
Split date range to year-month rows on SQL Server 2005
|
[
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
I have this table here,
**Options**
```
ID sType hValue
1 Late 10
2 NSF 20
```
Now what I want is, a single query to get an output like below:
```
Late NSF
10 20
```
2 separate columns with their respective hValues (in a single row). And should have separate column names so that I can use this query to Join with some other data.
I have tried Case statements But obviously it doesnt work. It gives me 2 separate rows with 1 NULL value in each column.
```
select Case when sType = 'Late' Then hValue End late,
Case When sType='NSF' Then hValue End nsf
from Options
where sType IN ('Late', 'NSF')
```
|
Add `Max` aggregate on top of your `case` statement
```
SELECT MAX(CASE WHEN sType = 'Late' THEN hValue END) late,
MAX(CASE WHEN sType = 'NSF' THEN hValue END) nsf
FROM Options
WHERE sType IN ('Late', 'NSF')
```
Considering that your `'Late'` or `'NSF'` will not be duplicated
|
PIVOT is just a shortcut of some other SQL statements. In most case, for PIVOT statement
```
-- Copied from T-SQL 2012 Fundamental.
SELECT ...
FROM <source_table_or_table_expression>
PIVOT(<agg_func>(<aggregation_element>)
FOR <spreading_element>
IN (<list_of_target_columns>)) AS <result_table_alias>;
```
it can be converted to
```
SELECT pass_through_columns,
<agg_func>(CASE WHEN <spreading_element> = '<target_columns1>' WHEN aggregation_element END) AS target_column1,
<agg_func>(CASE WHEN <spreading_element> = '<target_columns2>' WHEN aggregation_element END) AS target_column2,
...
FROM <source_table_or_table_expression>
GROUP BY pass_through_columns;
```
You can't talk PIVOT without aggregation function. In you case, try
```
select MAX(Case when sType = 'Late' Then hValue End) AS late,
MAX(Case When sType='NSF' Then hValue End) nsf
from Options
where sType IN ('Late', 'NSF')
```
There might be distinct value for each spreading\_element (Late, NSF), which makes MAX redundant, but it is not always the case.
|
Is there any alternative to do this except the PIVOT?
|
[
"",
"sql",
""
] |
I want to select only one row from a table. This row holds the maximum number in the table. I have tried to use MAX Fun but it didn't work for me. I use two tables to run my query, the first query returns more than one row
```
SELECT Rec_No FROM Records WHERE STATUS = 'Record Replaced';
select Item_No, Quantity from Rec_details
group by Item_No, Quantity
having Quantity=max(Quantity);
```
I have the problem in the second query as I always get these records
```
Item_No Quantity
---------- ----------
12507 1
12549 4
12100 8
12501 2
12201 7
12509 3
12080 1
```
My answer should check if the records replaced from the Records table and then select the maximum quantity and Item\_no from Rec\_Details. In my case it should be:
```
Item_No Quantity
---------- ----------
12201 7
```
|
Why does your second query not work...
```
select Item_No,
Quantity
from Rec_details
group by Item_No,
Quantity
having Quantity=max(Quantity);
```
You are grouping by both `Item_No` and `Quantity` and the `Item_No` appears to be the primary key and contain unique values so each group will only contain one row. The `HAVING` clause looks within the group so it will check that the value of `quantity` is the maximum value within that group but there is only one value within the group so this will always be true. Your query is the equivalent of:
```
SELECT DISTINCT
Item_No,
Quantity
FROM Rec_details;
```
Some other ways to get the maximum value:
[SQL Fiddle](http://sqlfiddle.com/#!4/d1d2a/4)
**Oracle 11g R2 Schema Setup**:
```
create table Rec_details (item_no, Quantity ) AS
SELECT 12507,1 FROM DUAL UNION ALL
SELECT 12549,4 FROM DUAL UNION ALL
SELECT 12100,8 FROM DUAL UNION ALL
SELECT 12501,2 FROM DUAL UNION ALL
SELECT 12201,7 FROM DUAL UNION ALL
SELECT 12509,3 FROM DUAL UNION ALL
SELECT 12080,1 FROM DUAL;
```
**Query 1 - Get one row with maximum `quantity` and latest `item_no` (using 1 table scan)**:
```
SELECT MAX( item_no ) KEEP ( DENSE_RANK LAST ORDER BY Quantity ) AS Item_no,
MAX( Quantity ) AS Quantity
FROM Rec_Details
```
**[Results](http://sqlfiddle.com/#!4/d1d2a/4/0)**:
```
| ITEM_NO | QUANTITY |
|---------|----------|
| 12100 | 8 |
```
**Query 2 - Get one row with maximum `quantity` and latest `item_no` (using 1 table scan)**:
```
SELECT *
FROM (
SELECT *
FROM Rec_details
ORDER BY Quantity DESC, Item_no DESC
)
WHERE ROWNUM = 1
```
**[Results](http://sqlfiddle.com/#!4/d1d2a/4/1)**:
```
| ITEM_NO | QUANTITY |
|---------|----------|
| 12100 | 8 |
```
**Query 3 - Get all rows with maximum `quantity` (using 1 table scan)**:
```
SELECT Item_no, Quantity
FROM (
SELECT r.*,
RANK() OVER ( ORDER BY Quantity DESC ) AS rnk
FROM Rec_details r
)
WHERE rnk = 1
```
**[Results](http://sqlfiddle.com/#!4/d1d2a/4/2)**:
```
| ITEM_NO | QUANTITY |
|---------|----------|
| 12100 | 8 |
```
**Query 4 - Get all rows with maximum `quantity` (using 2 table scans)**:
```
SELECT Item_no,
Quantity
FROM Rec_Details
WHERE Quantity = ( SELECT MAX( Quantity ) FROM Rec_Details )
```
**[Results](http://sqlfiddle.com/#!4/d1d2a/4/3)**:
```
| ITEM_NO | QUANTITY |
|---------|----------|
| 12100 | 8 |
```
**Query 5 - Get one row with maximum `Quantity` and latest `Item_No` using Oracle 12 Syntax (1 table scan):**
```
SELECT *
FROM Rec_Details
ORDER BY Quantity DESC, Item_No DESC
FETCH FIRST ROW ONLY;
```
**Query 5 - Get all rows with maximum `Quantity` using Oracle 12 Syntax (1 table scan):**
```
SELECT *
FROM Rec_Details
ORDER BY Quantity DESC
FETCH FIRST ROW WITH TIES;
```
|
One way to get the maximum in Oracle is to use `order by` and `rownum`:
```
select rd.*
from (select Item_No, Quantity
from Rec_details
order by quantity desc
) rd
where rownum = 1;
```
The `group by` seems unnecessary.
If there are multiple rows with the same quantity, you can also do:
```
select rd.*
from rec_details rd
where rd.quantity = (select max(quantity) from rec_details);
```
|
How can I SELECT the first row with MAX(Column value)?
|
[
"",
"sql",
"oracle",
"select",
""
] |
I have a table with following table
Table A
```
Text,id,Cid,CName,Aid,AName
Acc.sa is very Acc.pa and Acc.ba is awesome, 1,2,AB,1,CC
Acc.aa is awesome and Acc.sas is great,2,3,CC,1,CC
Acc.ee is not only great but Acc.sew is best,4,3,FF,1,CC
```
It should fetch all the words associated with Acc so the result should be
```
Did,id,Cid,CName,Aid,AName
Acc.sa,1,2,AB,1,CC
Acc.pa,1,2,AB,1,CC
Acc.ba,1,2,AB,1,CC
Acc.aa,2,3,CC,1,CC
Acc.sas,2,3,CC,1,CC
Acc.ee,4,3,FF,1,CC
Acc.sew,4,3,FF,1,CC
```
i.e. every search should have a new row
I tried the CHARINDEX and substring but I am not sure how to proceed in SELECT statement to use CHARINDEX and substring any help is highly appreciated.
|
```
with base10 as (
select n
from (values (0), (1), (2), (3), (4), (5), (6), (7), (8), (9)) v(n)
), k as (
select d2.n * 100 + d1.n * 10 + d0.n + 1 as n
from base10 d0 cross join base10 d1 cross join base10 d2
)
select
substring(a.Text, k.n, charindex(' ', a.Text, k.n) - k.n) as Did,
Id, Cid, CName, Aid, AName
from TableA a inner join k
on substring(a.Text, k.n, 4) = 'Acc.'
and k.n < len(a.Text) /* not necessary but optimizer might use it??? */
```
<http://sqlfiddle.com/#!6/a0f87/4> (*outputs a few extra columns*)
That will only handle strings about a thousand characters long. I suspect that's probably enough and you may even want to narrow the search length if that's slow.
I'm assuming that a space will immediately follow your "Acc." value which means it doesn't appear at the end of a line. That can be handled if necessary.
Since you're seeing errors it appears you have input lines that depart from the format you've specified. I don't see any other assumptions I'm making beyond the space character separator I mentioned.
For debugging you can replace the whole `substring()` line with this output to get a better idea of what's going on. Also add in a `where` clause to limit the rows to the ones that would cause an error:
```
select
'Bad offset' as Msg,
a.Text, k.n as StartOfAccBlick, charindex(' ', a.Text, k.n) as EndOfAccBlock
from ...
where
k.n - charindex(' ', a.Text, k.n) <= 0
```
|
The xml nodes method can be handy for parsing cell values into rows like this. E.g.:
```
select n.value('@s[1]', 'varchar(max)'), id, Cid, CName, Aid, AName
from Table_A ta
cross apply (select convert(xml, '<x s="' + replace(replace(replace(replace(replace(replace(ta.[Text],'&','&'),'>','>'),'<','<'),'''','''),'"','"'),' ','"/><x s="') + '"/>') xval) r
cross apply r.xval.nodes('*') x(n)
where n.value('@s[1]', 'varchar(max)') like 'Acc.%'
```
[SqlFiddle](http://sqlfiddle.com/#!3/da109c/2/0)
edit - escape the 5 invalid xml chars
|
Search and Extract a word from rows in SQL
|
[
"",
"sql",
"sql-server",
""
] |
I have a SQL Server 2014 temp table #SourceTable that looks like this below, where AllTheSamePerDOI is a bit field, defaulted to 0:
```
ID | DOI | Affiliations | SameAffiliationsPerDOI
----+-----+--------------+-----------------------
1 | 1 | Text A | 0
2 | 1 | Text A | 0
3 | 7 | Text CCC | 0
4 | 7 | Text CR | 0
5 | 7 | Text CCC | 0
6 | 9 | Text CCC | 0
```
What I would like to do is set the SameAffiliationsPerDOI field to a 1 only if all the records within the same DOI have the exact same text in all of their Affiations within that grouping. So the final result will look like this where DOI 1 and DOI 9 both have a 1 set since everything within each of those DOIs all has the same value in Affiliations for all their records. How Can I write a SQL statement to do this?
```
ID | DOI | Affiliations | SameAffiliationsPerDOI
----+-----+--------------+-----------------------
1 | 1 | Text A | 1
2 | 1 | Text A | 1
3 | 7 | Text CCC | 0
4 | 7 | Text CR | 0
5 | 7 | Text CCC | 0
6 | 9 | Text CCC | 1
```
|
I like to approach these problems using updatable CTEs and window functions:
```
with toupdate as (
select st.*,
min(Affiliations) over (partition by doi) as mina,
max(Affiliations) over (partition by doi) as maxa
from #SourceTable st
)
update toupdate
set SameAffiliationsPerDOI = 1
where mina = maxa;
```
You can also write this with `not exists`:
```
update #SourceTable st
set SameAffiliationsPerDOI = 1
where not exists (select 1
from #SourceTable st2
where st2.doi = st.doi and st2.Affiliations <> st.Affiliations
);
```
Which is faster probably depends on the distribution of values in the data and the indexes that are available.
|
```
UPDATE S
SET SameAffiliationsPerDOI = 1
FROM #SourceTable S
WHERE NOT EXISTS (SELECT 1 FROM #SourceTable S2 WHERE S2.DOI = S.DOI AND S2.Affiliations <> S.Affiliations)
```
|
SQL - Update a field if all in group are the same
|
[
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have an access database with following structure
```
ID EmployeeID DateTime
1 250 29/11/2015 6:00:00 AM
2 251 29/11/2015 6:01:25 AM
3 252 29/11/2015 7:30:05 AM
4 250 29/11/2015 1:30:45 PM
5 252 29/11/2015 1:32:20 PM
6 251 29/11/2015 4:36:41 PM
7 250 30/11/2015 8:30:50 AM
8 250 30/11/2015 3:45:22 PM
```
this table store times that each employee enters or exits. now I want to make a query to have this data:
first employee id, and the next two columns are enter and exit time
```
EmployeeID DateTime DateTime2
250 29/11/2015 6:00:00 AM 29/11/2015 1:30:45 PM
251 29/11/2015 6:01:25 AM 29/11/2015 4:36:41 PM
252 29/11/2015 7:30:05 AM 29/11/2015 1:32:20 PM
250 30/11/2015 8:30:50 AM 30/11/2015 3:45:22 PM
```
please help me to make this query
|
Probably not the greatest piece of sql but this will definitely give you what your after
```
SELECT e1.EmployeeID, e1.[DateTime] As StartDateTime, e2.[DateTime] As EndDateTime
FROM [EmployeeAccess] e1
INNER JOIN [EmployeeAccess] e2 ON
e1.Employeeid = e2.employeeid
and e1.datetime <> e2.datetime
and e1.DateTime < e2.datetime
and cast(e1.datetime as date) = cast(e2.datetime as date)
```
The join the same table together with the following rules:
1. Match by EmployeeID
2. ensure the datetimes are not the same exactly (removes joins of same entry)
3. ensure the datetime in e1 is less than datetime in e2 (removes joins where e2 is greater than e1)
4. ensure that only match same days entries (ensure only join same day matches)
|
If you have only one entry and exit time per day per employee, you can just group by the date which will sort correctly as well:
```
Select
EmployeeID,
Min([DateTime]) As DateTime1,
Max([DateTime]) As DateTime2
From
YourLogTable
Group By
Fix([DateTime]),
EmployeeID
```
|
How to calculate working time on this table?
|
[
"",
"sql",
"ms-access",
""
] |
Say I have a simple table in postgres as the following:
```
+--------+--------+----------+
| Car | Pet | Name |
+--------+--------+----------+
| BMW | Dog | Sam |
| Honda | Cat | Mary |
| Toyota | Dog | Sam |
| ... | ... | ... |
```
I would like to run a sql query that could return the column name in the first column and unique values in the second column. For example:
```
+--------+--------+
| Col | Vals |
+--------+--------+
| Car | BMW |
| Car | Toyota |
| Car | Honda |
| Pet | Dog |
| Pet | Cat |
| Name | Sam |
| Name | Mary |
| ... | ... |
```
[I found a bit of code that can be used to return all of the unique values from multiple fields into one column](https://dba.stackexchange.com/questions/102677/select-distinct-on-multiple-columns):
```
-- Query 4b. (104 ms, 128 ms)
select distinct unnest( array_agg(a)||
array_agg(b)||
array_agg(c)||
array_agg(d) )
from t ;
```
But I don't understand the code well enough to know how to append the column name into another column.
[I also found a query that can return the column names in a table.](https://dba.stackexchange.com/questions/22362/how-do-i-list-all-columns-for-a-specified-table) Maybe a sub-query of this in combination with the "Query 4b" shown above?
|
[SQL Fiddle](http://www.sqlfiddle.com/#!15/ced66/6)
```
SELECT distinct
unnest(array['car', 'pet', 'name']) AS col,
unnest(array[car, pet, name]) AS vals
FROM t
order by col
```
|
It's bad style to put set-returning functions in the `SELECT` list and not allowed in the SQL standard. Postgres supports it for historical reasons, but since `LATERAL` was introduced Postgres 9.3, it's largely obsolete. We can use it here as well:
```
SELECT x.col, x.val
FROM tbl, LATERAL (VALUES ('car', car)
, ('pet', pet)
, ('name', name)) x(col, val)
GROUP BY 1, 2
ORDER BY 1, 2;
```
You'll find this `LATERAL (VALUES ...)` technique discussed under [the very same question on dba.SE you already found yourself](https://dba.stackexchange.com/questions/102677/select-distinct-on-multiple-columns). Just don't stop reading at the first answer.
Up until Postgres **9.4** there was still an exception: "parallel unnest" required to combine multiple set-returning functions in the `SELECT` list. Postgres 9.4 brought a [new variant of `unnest()`](http://www.postgresql.org/docs/current/interactive/functions-array.html#ARRAY-FUNCTIONS-TABLE) to remove that necessity, too. More:
* [Unnest multiple arrays in parallel](https://stackoverflow.com/questions/27836674/passing-arrays-to-stored-procedures-in-postgres/27854382#27854382)
The new function is also does not derail into a Cartesian product if the number of returned rows should not be exactly the same for all set-returning functions in the SELECT list, which is (was) a very odd behavior. The new syntax variant should be preferred over the now outdated one:
```
SELECT DISTINCT x.*
FROM tbl t, unnest('{car, pet, name}'::text[]
, ARRAY[t.car, t.pet, t.name]) AS x(col, val)
ORDER BY 1, 2;
```
Also shorter and faster than two `unnest()` calls in parallel.
Returns:
```
col | val
------+--------
car | BMW
car | Honda
car | Toyota
name | Mary
name | Sam
pet | Cat
pet | Dog
```
`DISTINCT` or `GROUP BY`, either is good for the task.
|
Return column name and distinct values
|
[
"",
"sql",
"postgresql",
"distinct",
"set-returning-functions",
""
] |
Company table structure:
```
(`id`=`1`, `name`=`CompanyName`, `members`=`3,52,134,21`)
```
The numbers in the `members` column are the user id's added to this company.
When user with `id = 3 OR 52 OR 134 OR 21` is logged in the row above should be returned with a MySQL query.
Is this possible with a query or do I have to edit my table structure?
|
Try:
```
SELECT * FROM tbl_name WHERE FIND_IN_SET('3',members);
```
**Note:** Never store data in comma separated format. If it is not late yet, then make one more table and normalize the structure. By normalizing the structure, it will be easy and fast searching by giving indexing to the column.
table name: `company_users`
```
pk_id member_id company_id(foriegn_key of company_table)
1 3 1
2 52 1
3 21 1
```
|
Use [**FIND\_IN\_SET()**](http://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_find-in-set) function:
Try this:
```
SELECT u.*
FROM Company c
INNER JOIN company_users u ON FIND_IN_SET(u.id, c.members)
WHERE c.id = 1;
```
|
How to find id in MySQL column array
|
[
"",
"mysql",
"sql",
"select",
"join",
"find-in-set",
""
] |
This is a simple example of the problem I am facing. I have two tables, Job and Person. A Person can work at 1 or more jobs. I need to return one column of data with the job ids of a particular person, but if the person works at job\_id = 'god', then it should return all the job ids. I am using a framework and this must be done in a SQL statement and not PLSQL(which is why I am struggling with this).
```
**JOB**
JOB_ID | JOB_NAME
doc Doctor
ba Barber
god Admin
**PERSON**
PERSON_ID | JOB_ID
Jeff doc
Jeff ba
Mary ba
Thor god
```
So far I am able to return all the jobs where a user belongs to, but I need to somehow return all the jobs if in the person person has a job\_id ='god.'
```
select DISTINCT p.JOB_ID
from PER_JOBS p,PER_PEOPLE pu
WHERE
p.JOB_ID= pu.JOB_ID
and pu.PERSON_ID = 'thor';
```
So if if I select Jeff: doc and ba should be returned while if I select Thor: doc,ba,and god should be returned.
|
You need to do a join here and then add a where clause to get what you want. The join look like this
```
SELECT P.PERSON_ID, J.JOB_NAME
FROM PERSON P
JOIN JOB J ON (P.JOB_ID = J.JOB_ID) OR P.JOB_ID = 'god'
```
This will give you a list of people and their jobs. You could even make this a view.
Now just select the person you want
```
SELECT P.PERSON_ID, J.JOB_NAME
FROM PERSON P
JOIN JOB J ON (P.JOB_ID = J.JOB_ID) OR P.JOB_ID = 'god'
WHERE P.PERSON_ID = 'thor';
```
|
Here is the query:
```
select distinct j.job_id from job j join person p
on ((j.job_id = p.job_id and p.job_id <> 'god') or p.job_id = 'god')
where p.person_id = 'Thor';
JOB_ID
----------
doc
ba
god
select distinct j.job_id from job j join person p
on ((j.job_id = p.job_id and p.job_id <> 'god') or p.job_id = 'god')
where p.person_id = 'Jeff';
JOB_ID
----------
doc
ba
```
|
Conditional pure sql query
|
[
"",
"sql",
"oracle",
"oracle11g",
""
] |
I'm running into an issue with which I can't figure out how to correctly configure a join. I'm using reporting software that utilizes the (+) indicators in the WHERE clause for our Oracle database. I have two tables:
CHECK and TRANSACTION. A check can have multiple transactions, but a transaction doesn't necessarily have a corresponding check.
Both tables have indicators identifying current records called CURRENT that is either a 'Y' or 'N'.
Join option 1:
```
Select *
FROM TXN,CHK
WHERE
TXN.CHK_ID = CHK.CHK_ID(+)
and TXN.CURRENT = 'Y'
and CHK.CURRENT = 'Y'
```
Join option 2:
```
Select *
FROM TXN,CHK
WHERE
TXN.CHK_ID = CHK.CHK_ID(+)
and TXN.CURRENT = 'Y'
and CHK.CURRENT(+) = 'Y'
```
These joins produce different results, and I can't seem to figure out what effect the extra outer join indicator is having when applied to the CHK.CURRENT field. The query with the extra indicator produces a larger result set. Can someone help explain what's going on here?
|
I'm going to explain this by using equivalent "ANSI JOIN" syntax:
### Option 1
```
SELECT *
FROM TXN
LEFT JOIN CHK
ON TXN.CHK_ID = CHK.CHK_ID
WHERE TXN.CURRENT = 'Y'
AND CHK.CURRENT = 'Y'
```
### Option 2
```
SELECT *
FROM TXN
LEFT JOIN CHK
ON TXN.CHK_ID = CHK.CHK_ID
AND CHK.CURRENT = 'Y'
WHERE TXN.CURRENT = 'Y'
```
As you can see, in option 1, your constant predicates are applied *after* the `LEFT JOIN` table expression is specified, i.e. on the result of the `LEFT JOIN`.
In option 2, one of your constant predicates is part of the `LEFT JOIN` expression.
### How does `LEFT JOIN` work?
The idea of a `LEFT JOIN` is that it will return all rows from the *LEFT* side of the `JOIN` expression, regardless if there is a matching row on the other side, given the join predicate. So, in option 2, regardless if you find a row in `CHK` with `CURRENT = 'Y'` for a row in `TXN`, the row in `TXN` is still returned. This is why you get more rows in option 2.
Also, this example should explain why you should prefer the "ANSI JOIN" syntax. From a maintenance / readability perspective, it is much more clear what your query is doing.
|
.The `(+)` operator tells Oracle that a predicate is part of an outer join rather than a filter predicate that can be applied after the join. Using the SQL 99 outer join syntax, the first query is equivalent to
```
SELECT *
FROM txn
left outer join chk
on( txn.chk_id = chk.chk_id )
WHERE txn.current = 'Y'
AND chk.current = 'Y'
```
while the second is equivalent to
```
SELECT *
FROM txn
left outer join chk
on( txn.chk_id = chk.chk_id AND
chk.current = 'Y')
WHERE txn.current = 'Y'
```
Logically, in the first case, you do the outer join but then all the rows where `chk.current` was `NULL` get filtered out. In the second case, the `chk.current = 'Y'` condition doesn't filter out any rows, it just controls whether a matching row is found in `chk` or whether a left outer join is performed.
|
Oracle (+) outer join and constant values
|
[
"",
"sql",
"oracle",
"left-join",
""
] |
Hello guys I can not figure out how to write query which would return results where which provider ids are assigned to all operator ids.
```
operatorid-providerid
1 [1] - [3]
2 [2] - [1]
3 [3] - [2]
4 [1] - [3]
5 [2] - [2]
6 [3] - [1]
7 [1] - [2]
8 [2] - [3]
9 [3] - [1]
10 [1] - [5]
11 [2] - [5]
```
Expected result :
```
operator-provider
1 [1] - [3]
2 [2] - [1]
3 [3] - [2]
4 [1] - [3]
5 [2] - [2]
6 [3] - [1]
7 [1] - [2]
8 [2] - [3]
9 [3] - [1]
```
providerid 5 is not shown because it was not assigned to operatorid 3
I have tried many options but with no success here is last query. I would post code but it won't make sense.
Code :
```
SELECT t2.operatoriausID,t2.papildomosPaslaugosID
FROM OperatoriausPapildomaPaslauga t2,
(SELECT t5.papildomosPaslaugosID,count(t5.papildomosPaslaugosID) c
FROM OperatoriausPapildomaPaslauga t5
group by t5.papildomosPaslaugosID) d
WHERE d.c = 3
```
|
```
with cte1 as
( select distinct(operatorid) from table )
, cte2 as
( select providerid
from table
join cte1
on cte1.operatorid = table.operatorid
group by providerid
having count(distinct(table.operatorid)) = ( select count(*) from cte1 )
)
select table.*
from table
join cte2
on table.providerid = cte2.providerid
```
or this maybe even works
```
select table.*
from table
join ( select providerid
from table
group by providerid
having count(distinct(operatorid)) = ( select count(distinct(operatorid))
from table )
) tt
on table.providerid = tt.providerid
```
|
```
select table.*
from table
where table.providerID in (
select table.providerID
from table
group by table.providerID
having count(distinct table.operatorID) =
(select count(distinct table.operatorID)
from table)
)
```
|
SQL get results where column values have same value in other column
|
[
"",
"sql",
""
] |
RDMS: MySQL
I'm designing a private messaging thread system and have the following schema laid out for the messaging system (simplified). I need to select every conversation that an account with a known ID (we'll say '1') is in, the last message that was sent in the conversation, and the username of the other account that account '1' is chatting with. Grouped by the conversation id. (imagine an inbox page like Facebook has)
My SQL knowledge is limited (I'm going to spend the weekend advancing it) but it the meantime does anyone have a query that would get the job done?
Thanks in advance. Let me know if you need more info.
Schema
[](https://i.stack.imgur.com/hQb99.png)
EDIT: I believe I may have found a solution (still needs proper testing).
I'm still accepting answers as I'm not sure this is the best route to go yet. I've reviewed the current answers posted and they are getting me in the right direction but so far aren't returning the right results.
Here's what I've come up with.
```
SELECT account_has_conversations.account_id, messages.*, account.username FROM messages, account, account_has_conversations WHERE account_has_conversations.conversation_id IN
(
SELECT account_has_conversations.conversation_id FROM account_has_conversations WHERE account_has_conversations.account_id = '1'
)
AND account_has_conversations.account_id != '1' AND account_has_conversations.account_id = account.account_id
AND account_has_conversations.conversation_id = messages.conversation_id
GROUP BY account_has_conversations.conversation_id
```
(I probably should have created some aliases haha)
|
First, you don't have any text fields in any of the tables in your pictured schema - so I don't know where you're storing the actual message content or how to retrieve it. That said, this query should work for you and you can just add the field that you need.
This will get you the username, the last message received, and the sending username for all of the selected user's conversations. I will ASSUME the message content is in the messages table and is stored in a field called "message\_text":
```
DECLARE @AccountID int = 1 //For testing, but this should be parameterized
SELECT A.username as [User],
A2.username as [SendingUser]
M.message_text as [LastMessage]
FROM account A
JOIN account_has_conversations AHC
ON A.account_id = AHC.account_id
JOIN conversation C
ON AHC.conversation_id = C.conversation_id
JOIN
(
Select
sender_account_id,
conversation_id,
message_text,
row_number() over(partition by conversation_id order by time_sent desc) as rn
FROM messages
) as M
ON C.conversation_id = M.conversation_id
AND M.sender_account_id <> @AccountID //This prevents a circular join in case the last message was sent by the user. You may not need this, but it's impossible to tell based on the information you provided.
JOIN account A2
ON M.sender_account_id = A2.account_ID
WHERE rn = 1
AND A.account_id = @AccountID
```
|
I have tested this, but maybe this will get you in the right direction.
```
Select m.*
from account a
inner join account_has_conversation ahc
on (a.account_id = account_id)
inner join messages m
on (ahc.conversation_id = m.conversation_id)
where a.account_id = 1
```
I would add:
* Your conversation table doesn't really seem to have any value.
* Group By is great, but you're going to need to squeeze all your results down as well. By that I mean that if you want to squish ten rows into one (grouping by one of the columns where all the rows have the same value in that column), you'll need to have all the other columns in an aggregate function.
|
SQL - How would I select data involving multiple tables?
|
[
"",
"mysql",
"sql",
""
] |
I have T-SQL Table below.
```
ID Cost MaxCost
-------------------------------
2 200 300
3 400 1000
6 20 100
```
The above table must have 10 rows with IDs 1 to 10. So its missing 7 rows. How do i insert missing rows with proper ID. The cost & maxcost for missing rows will be zero. Do i need to create a temp table that holds 1 to 10 numbers?
|
No need for temp table, simple tally derived table and `LEFT OUTER JOIN` are sufficient:
```
CREATE TABLE #tab(ID INT, Cost INT, MaxCost INT);
INSERT INTO #tab(ID, Cost, MaxCost)
VALUES (2, 200,300),(3, 400, 1000) ,(6, 20, 100);
DECLARE @range_start INT = 1
,@range_end INT = 10;
;WITH tally AS
(
SELECT TOP 1000 r = ROW_NUMBER() OVER (ORDER BY name)
FROM master..spt_values
)
INSERT INTO #tab(id, Cost, MaxCost)
SELECT t.r, 0, 0
FROM tally t
LEFT JOIN #tab c
ON t.r = c.ID
WHERE t.r BETWEEN @range_start AND @range_end
AND c.ID IS NULL;
SELECT *
FROM #tab
ORDER BY ID;
```
`LiveDemo`
**EDIT:**
Tally table is simply number table. There are many ways to achieve it with [subquery](https://stackoverflow.com/questions/21425546/how-to-generate-a-range-of-numbers-between-two-numbers-in-sql-server):
* recursive cte
* `ROW_NUMBER()` from system table that holds many values (used here)
* `UNION ALL` and `CROSS JOIN`
* `VALUES(...)`
* using `OPENJSON` (SQL Server 2016+)
* ...
The `TOP 1000` will generate only 1000 records if you know that you need more you can use:
```
SELECT TOP 1000000 r = ROW_NUMBER() OVER (ORDER BY (SELECT 1))
FROM master..spt_values c
CROSS JOIN master..spt_values c2;
```
|
Since your number of rows is low you could just define the data explicitly...
```
CREATE TABLE Data(ID INT, Cost INT, MaxCost INT);
INSERT INTO Data(ID, Cost, MaxCost) VALUES(2, 200, 300);
INSERT INTO Data(ID, Cost, MaxCost) VALUES(3, 400, 1000);
INSERT INTO Data(ID, Cost, MaxCost) VALUES(6, 20, 100);
```
and the query...
```
select *
from (VALUES(1),(2),(3),(4),(5),(6),(7),(8),(9),(10)) RowNums (ID)
left outer join Data on RowNums.ID = Data.ID
```
The first part defines a column ID with rows 1-10, it then left outer joins to your data. The beauty of this is that it is very readable.
|
TSQL: How do i detect and insert missing records
|
[
"",
"sql",
"sql-server",
"t-sql",
""
] |
I am using SQL Server 2008 and want to convert table data into json format. Can I convert it directly through firing query?
|
Built in support for formatting query results is added in SQL Server 2016 and it will be available in Azure Database.
In older versions you would need to use CLR or some heavy TSQL like:
* [Producing JSON Documents from SQL Server queries via TSQL](https://www.simple-talk.com/sql/t-sql-programming/producing-json-documents-from-sql-server-queries-via-tsql/)
|
I have created a stored procedure that can take your table and output JSON. You can find it at
* [GitHub - SQLTableOrViewToJSON](https://github.com/ahliana/SQLTableOrViewToJSON)
Once you run the stored procedure, you can output your table by making a call like the following:
```
EXEC SQLTableOrViewToJSON 'MyTable', 'C:\WhereIStowMyJSON\'
```
|
How to convert data to json format in SQL Server 2008?
|
[
"",
"sql",
"json",
"sql-server",
"sql-server-2008",
""
] |
I'm strugling with what on the first sight appeared to be simple SQL query :)
So I have following table which has three columns: PlayerId, Gender, Result (all of type integer).
What I'm trying to do, is to select distinct players of gender 2 (male) with number of each results.
There are about 50 possible results, so new table should have 51 columns:
|PlayerId | 1 | 2 | 3 | ... | 50 |
So I would like to see how many times each individual male (gender 2) player got specific result.
\*\*\* In case question is still not entirely clear to you: After each game I insert a row with a player ID, gender and result (from 1 - 50) player achieved in that game. Now I'd like to see how many times each player achieved specfic results.
|
If there are 50 results and you want them in columns, then you are talking about a pivot. I tend to do these with conditional aggregation:
```
select player,
sum(case when result = 0 then 1 else 0 end) as result_00,
sum(case when result = 1 then 1 else 0 end) as result_01,
. . .
sum(case when result = 50 then 1 else 0 end) as result_50
from t
group by player;
```
You can choose a particular gender if you like, with `where gender = 2`. But why not calculate all at the same time?
|
try
```
select player, result, count(*)
from your_table
where Gender = 2
group by player, result;
```
|
Selecting count by row combinations
|
[
"",
"sql",
"sql-server",
"database",
""
] |
I need to select the last register for each `budget_id`, which is a foreign key.
For example, if my table is:
```
id | budget_id | comment
1 | 8 | Test 1
2 | 8 | Test 2
3 | 5 | Test 1
4 | 5 | Test 2
```
I need to retrieve like this:
```
id | budget_id | comment
4 | 5 | Test 2
2 | 8 | Test 2
```
But it is always showing the first register for each `budget_id`. Intead of `Test 2`, it shows `Test 1`.
Here is my SQL so far:
```
SELECT *
FROM note
GROUP BY budget_id
ORDER BY id DESC
```
I have tried adding `HAVING`, sub selects selecting the `MAX` field `created_at`, but nothing.
**EDIT**
After doing what I was told, I kind of managed to make it work, but now the query only returns the SECOND register of each `budget_id`. Here is my SQL:
```
SELECT MAX(n.id),
c.name,
MAX(n.comment)
FROM note n,
budget b,
customer c
WHERE n.budget_id = b.id
AND b.customer_id = c.id
GROUP BY n.budget_id
ORDER BY n.id DESC
```
|
I think the query is this
```
select id, budget_id,[comment]
from note
where id in
(select max(id)
from note
group by budget_id)
order by id desc
```
In your question , I only see that you want get the max id for every budget\_id , if your purpose is not this ,please give more sample or describe clearly!
|
You must select max on id and comment then group by budget\_id.
SELECT max(id) id, max(comment) as comment, budget\_id from table group by budget\_id order by max(id)
|
Select last register per group by
|
[
"",
"mysql",
"sql",
"symfony",
""
] |
I am trying to get two columns, `frequency` and `frequency - min(frequency)` but all I see is zero for the second column. What could possibly be wrong?
```
SELECT
frequency, frequency - min(frequency)
FROM
words
GROUP BY id
ORDER BY frequency;
```
[](https://i.stack.imgur.com/Xw68C.png)
|
Your query groups by the unique value of frequency. In each such group, the minimal frequency is just the frequency itself, so you always get `0` when subtracting the two. Instead, you could use the windowing version of `min`:
```
SELECT frequency, frequency - MIN(frequency) OVER() AS diff
FROM words
ORDER BY frequency
```
|
Add a sub-query that returns the min frequency value:
```
SELECT
frequency, frequency - (select min(frequency) from words)
FROM
words
ORDER BY frequency;
```
**Edit:**
Wrap it up in a derived table:
```
SELECT frequency, frequency - minfreq, frequency + minfreq
FROM words
CROSS JOIN (select min(frequency) minfreq from words) dt
ORDER BY frequency
```
|
SQL min function
|
[
"",
"sql",
"postgresql",
"select",
"min",
""
] |
I have a Visual Studio sql project with a table defined like the following:
```
CREATE TABLE [dbo].[Hoerses]
(
[HoersId] INT NOT NULL PRIMARY KEY,
[DatePurchased] datetime NOT NULL CONSTRAINT [DF_Hoerses_DatePurchased] DEFAULT DATETIMEFROMPARTS(1985,01,01,0,0,0,0)
)
```
When I target a preexisting SQL database with a "Script" command
```
sqlpackage.exe /Action:Script /SourceFile:DatabaseProject1.dacpac /Profile:publish.xml /OutputPath:deployscript_test.sql /TargetPassword:redacted
```
Then I get the following generated SQL even though the constraint had the same name and definition before & after:
```
PRINT N'Dropping [dbo].[DF_Hoerses_DatePurchased]...';
GO
ALTER TABLE [dbo].[Hoerses] DROP CONSTRAINT [DF_Hoerses_DatePurchased];
GO
PRINT N'Creating [dbo].[DF_Hoerses_DatePurchased]...';
GO
ALTER TABLE [dbo].[Hoerses]
ADD CONSTRAINT [DF_Hoerses_DatePurchased] DEFAULT DATETIMEFROMPARTS(1985,01,01,0,0,0,0) FOR [DatePurchased];
GO
PRINT N'Update complete.';
GO
```
(My main concern with trying to prevent this superfluous re-creation is because I occasionally see a "Lock request time out period exceeded." error when it's trying to drop a constraint during actual deployments/publishing)
|
The problem was apparently in the use of `DATETIMEFROMPARTS`.
If I instead declare the table as
```
CREATE TABLE [dbo].[Hoerses]
(
[HoersId] INT NOT NULL PRIMARY KEY,
[DatePurchased] datetime NOT NULL CONSTRAINT [DF_Hoerses_DatePurchased] DEFAULT '1985-01-01'
)
```
Then SqlPackage.exe no longer tries to drop & re-add the constraint.
|
Dacpac deployment works by comparing an XML construct of the Database schema with one from your VS project.
Sometimes this process is confused by syntactic niceties resulting in repeating changes such as you describe.
My recommendation is that you go to a deployed database, script out the troublesome object and paste that back over the implementation your Visual Studio file for that object. This resolves the apparent discrepancy so the deployment is no longer fooled into believing it has a change to implement.
|
How can I prevent SqlPackage.exe from dropping and re-creating constraints when deploying a dacpac?
|
[
"",
"sql",
"sql-server",
"sqlpackage",
""
] |
In database systems, should every table have a primary key?
For example I have a table `table1(foreignkey1,foreignkey2,attribute)` like `this.table1` does not have a primary key.
Should I define a primary key for this table like `table1id`?
|
This is a subjective question, so I hope you don't mind me answering with some opinion :)
In the vast majority of tables I've made – I'm talking 95%+ – I've added a primary key, and been glad I did. This is either the most critical unique field in my table (think "social security number") or, more often than not, just an auto-incrementing number that allows me to quickly and easily refer to a field when querying.
This latter use is the most common, and it even has its own name: a "surrogate" or "synthetic" key. This is a value auto-generated by the database and not derived from your application data. If you want to add relations between your tables, this surrogate key is immediately helpful as a foreign key. As someone else answered, these keys are so common that MySQL likes to add one even if you don't, so I'd suggest that means the consensus is very heavily biased towards adding primary keys.
One other thing I like about primary keys is that they help convey your intent to others reading your table schemata and also to your DMBS: "this bit is how I intend to identify my rows uniquely, don't let me try to break that rule!"
To answer your question specifically: no, a primary key is *not* necessary. But realistically if you intend to store data in the table for any period of time beyond a few minutes, I would very strongly recommend you add one.
|
No, it is not required for every table to have a primary key. Whether or not a table should have a primary key is based on requirements of your database.
Even though this is allowed it is bad practice because it allows for one to add duplicate rows further preventing the unique identification of rows. Which contradicts the underline purposes of having a database.
|
Is a primary key necessary?
|
[
"",
"mysql",
"sql",
""
] |
I am asking you how can I mimic this logic in SQL:
```
SELECT var1, var2 FROM table1,WHERE var1 = COUNT(table1.status == 1) AND var2 = COUNT(table2.status == 2)
```
I want to store in `var1` the number of entries that have `status = 1` and in `var2` the number of entries which have `status = 2` in a single `SELECT`.
|
You can use `COUNT` combined with `CASE`:
```
SELECT
COUNT(CASE WHEN t1.Status = 1 THEN 1 END) AS var1,
COUNT(CASE WHEN t1.Status = 2 THEN 1 END) AS var2
FROM table1 t1;
```
Alternatively you can use `SUM`:
```
SELECT
SUM(t1.status = 1) AS var1,
SUM(t1.status = 2) AS var2
FROM table1 t1;
```
|
If your table is large and has an index on the `status` column, you need to be able to use an index to get fast exection (two index lookups are faster than one table scan), and that requires to filter the rows with WHERE.
If you can handle the result as two rows, use a [compound query](http://www.sqlite.org/lang_select.html#compound):
```
SELECT count(*) FROM Table1 WHERE status = 1
UNION ALL
SELECT count(*) FROM Table1 WHERE status = 2;
```
If you need the results in two columns, you can use subqueries:
```
SELECT (SELECT count(*) FROM Table1 WHERE status = 1) AS var1,
(SELECT count(*) FROM Table1 WHERE status = 2) AS var2;
```
|
SELECT query for two variables in the same table
|
[
"",
"sql",
"database",
"sqlite",
""
] |
I have a table for recording license usage. Each license usage needs to be associated with a user and a host machine. The table definition looks like this.
```
create table if not exists per_user_fact
(
per_user_fact_id int unsigned not null auto_increment,
time_of_day char(16) not null,
license_served_id smallint unsigned not null,
license_hours numeric(10,2) not null,
role_name varchar(64) null,
user varchar(128) not null,
host varchar(128) not null,
primary key (per_user_fact_id),
foreign key (license_served_id) references served_license(served_license_id),
foreign key (user, host) references user_host(username, hostname)
);
```
I want to normalize this table so that the user/host values, which are repetitive, are moved to a new table like this.
```
create table if not exists user_host
(
username varchar(64) not null,
hostname varchar(128) not null,
primary key (username, hostname)
);
```
For the **user\_host** table, what kind of primary key should I pick up - natural or surrogate? I can think of the following governing factors.
1. If the primary key is natural, that is a composite of user and host names, the parent table **per\_user\_fact** will not need additional joins to find out user and host names.
2. If the primary key is natural, there will be waste of storage as the user and host names values will be duplicated in both the tables.
3. If the primary key is surrogate, the additional join will be needed for the parent table to get the values for user and host names.
4. If the primary key is surrogate, the indexing on the user\_host table will be faster.
Please advise.
|
I am a big fan of using surrogate primary keys, even in this case. The cost of the additional join is negligible when you are joining to a clustered primary key.
In addition, assuming that `username` and `hostname` are (together) longer than four or so characters, the surrogate key saves space. In fact, you might find that a surrogate key results in *faster* queries because the data in `per_user_fact` is smaller. Smaller tables occupy fewer data pages, resulting in fewer I/Os.
Another advantage of a surrogate key is the opportunity to change user names and host names *without* modifying any other tables. If you are using data fields for joins, then modifying the values requires updating multiple tables -- a more cumbersome operation.
I also like surrogate identity/serial/auto increment keys because they also capture insertion order in the table. Of course, there are other methods (my tables typically have a `CreatedAt` column which defaults to the insertion time). But, the surrogate key can also play that role.
These reasons do not constitute a "right" answer to the question. There are valid reasons for not using surrogates. For me, though, almost all my tables have such primary keys.
|
Given the situation explained in the question, i would second the use of a Surrogate key. while a natural PK will give you some advantage on the indexing front, for all practical purposes, the use of surrogates will offer more advantages.
Surrogates keep your tables slimmer, give you auditing possibilities etc.
|
Lookup Table -- Natural or Surrogate key as primary key?
|
[
"",
"sql",
"join",
"lookup",
"surrogate-key",
"natural-key",
""
] |
Below is my theater table:
```
create table theater
(
srno integer,
seatno integer,
available boolean
);
insert into theater
values
(1, 100,true),
(2, 200,true),
(3, 300,true),
(4, 400,false),
(5, 500,true),
(6, 600,true),
(7, 700,true),
(8, 800,true);
```
I want a sql which should take input as 'n' and returns me the first 'n' consecutive available seats, like
* if n = 2 output should be 100,200
* if n = 4 output should be 500,600,700,800
NOTE: I am trying to build an query for postgres 9.3
|
thanks guys, but i have done achieved it like below,
```
select srno, seatno from (
select *, count(0) over (order by grp) grp1 from (
select t1.*,
sum(group_flag) over (order by srno) as grp
from (
select *,
case
when lag(available) over (order by srno) = available then null
else 1
end as group_flag
from theater
) t1 ) tx ) tr where tr.available=true and tr.grp1 >= 2 limit 2
```
|
In *SQL-Server* you can do It in following:
```
DECLARE @num INT = 4
;WITH cte AS
(
SELECT *,COUNT(1) OVER(PARTITION BY cnt) pt FROM
(
SELECT tt.*
,(SELECT COUNT(srno) FROM theater t WHERE available <> 'true' and srno < tt.srno) AS cnt
FROM theater tt
WHERE available = 'true'
) t1
)
SELECT TOP (SELECT @num) srno, seatno, available
FROM cte
WHERE pt >= @num
```
**OUTPUT**
```
srno seatno available
5 500 true
6 600 true
7 700 true
8 800 true
```
|
sql : get consecutive group 'n' rows (could be inbetween)
|
[
"",
"sql",
"postgresql-9.3",
"gaps-and-islands",
""
] |
How can I select specific number of date (let it be third) for all CustomerID in a row
for example I have DB looks like
```
+---------+------------+------------+------------+-----------+
| OrderID | CustomerID | EmployeeID | OrderDate | ShipperID |
+---------+------------+------------+------------+-----------+
| 10308 | 2 | 7 | 1996-09-18 | 3 |
| 10365 | 3 | 3 | 1996-11-27 | 2 |
| 10355 | 4 | 6 | 1996-11-15 | 1 |
| 10383 | 4 | 8 | 1996-12-16 | 3 |
| 10278 | 5 | 8 | 1996-08-12 | 2 |
| 10280 | 5 | 2 | 1996-08-14 | 1 |
| 10384 | 5 | 3 | 1996-12-16 | 3 |
| 10265 | 7 | 2 | 1996-07-25 | 1 |
| 10297 | 7 | 5 | 1996-09-04 | 2 |
| 10360 | 7 | 4 | 1996-11-22 | 3 |
| 10436 | 7 | 3 | 1997-02-05 | 2 |
+---------+------------+------------+------------+-----------+
```
and as the output we have to get
```
╔══╦════════════╦══╦════════════╦══╗
║ ║ CustomerID ║ ║ OrderDate ║ ║
╠══╬════════════╬══╬════════════╬══╣
║ ║ 5 ║ ║ 1996-12-16 ║ ║
║ ║ 7 ║ ║ 1996-11-22 ║ ║
╚══╩════════════╩══╩════════════╩══╝
```
something like this
I use MySQL
|
```
SELECT
CustomerIds.CustomerID
,(SELECT OrderDate FROM Table1
WHERE Table1.CustomerID = CustomerIds.CustomerID
ORDER BY OrderDate ASC
LIMIT 1 OFFSET 2) AS OrderDate
FROM
(SELECT CustomerID
FROM Table1
GROUP BY CustomerID
HAVING COUNT(*) >= 3) AS CustomerIds;
```
[SQLFiddle](http://sqlfiddle.com/#!9/9bb4b/6)
|
Try this,
```
select customerid , orderdate from table where GROUP BY customerid
```
|
select n-th row of certain key SQL
|
[
"",
"mysql",
"sql",
"database",
""
] |
I have a string that looks like: `'10,244,566'`
How do I get the `2nd` item?
for the above string the item is `244`.
The string always looks like `'x,y,z'`.
I don't see anything helpful in the manual <http://www.postgresql.org/docs/9.1/static/functions-string.html#FUNCTIONS-STRING-OTHER>
**EDIT:**
The string is a text that I recive from other component that I have no control over. Assume that the user enters 3 parmeters.. this component save it as string and pass the string to me. I need to break it into the 3 paremeters. For my need i only case about the 2nd paremter.
I can do this:
```
select string_to_array(string, ',', null)
```
for the above example it will give me `{10,244,566}` as
```
text[]
```
how do it get the 2nd item in the array?
|
Looks like a job for [`split_part`](http://www.postgresql.org/docs/9.1/static/functions-string.html#FUNCTIONS-STRING-OTHER) ([sql fiddle](http://sqlfiddle.com/#!15/9eecb7db59d16c80417c72d1e1f4fbf1/5040/0)):
```
select split_part('10,244,566', ',', 2);
```
|
Splitting strings contained in the database isn't really something that databases were designed for.
There's different options here:
1. restructure your data to make strings like `10,244,566`
1. three columns, if it's always three values, or
2. a n-to-m mapping with a second table
2. program the splitting in whatever language you're using to talk to postgresql
3. hack together a relatively hard to debug, relatively slow, relatively "far away from what you want" extractor in postgresql: `select substring(the_column from ',\d+,') from the_table`
I **strongly** recommend doing option 1.1. if possible, or option 1.2. if the string might not always represent three values.
As it is now, you're abusing your database's string data type to store three integers, which is a waste of space, slow, error-prone, an anti-pattern and hard to maintain.
**EDIT**: I have to take back a bit about *you* abusing a database: whoever is pushing that string into postgresql is abusing the database, so that you now have to deal with it :(
**EDIT** your clarification is critical:
> I am proccessing the string in postgresql function. My function is connecting to another component (lets say paypal) and reciveing a data burst as STRING. I need to convert this String for items to store in my PostgreSQL DB. So I catualy saves the 2nd parmeter as integer
Awesome, so just use the programming language you're using to get your string from let's say paypal and split it to three parts there. There's no reason postgreSQL would do that better than you could, and you would have the conceptual benefit of transporting well-formed data to your database.
|
How to get an item from string in postgresql?
|
[
"",
"sql",
"postgresql",
""
] |
i got 3 Tables
```
Player: player_id, player_name
Date: date_id, date_value
PlayerOnDate: pod_id, player_id, date_id
```
how can i inser something like
```
INSERT INTO `playerondate`(`player_on_date_id`, `player_id`, `date_date_id`) VALUES (
NULL,
SELECT player_id
WEHRE player_name LIKE 'aName',
SELECT date_id
WEHRE date_value LIKE '12122015'
)
```
|
There is a specific SQL statement for that INSERT INTO ... SELECT
```
INSERT INTO `playerondate`(`player_on_date_id`, `player_id`, `date_date_id`)
SELECT NULL, player_id, date_id
FROM playerondate
WHERE player_name = 'aName' AND date_value LIKE '12122015'
```
|
Just add a FROM
```
SELECT player_id FROM Player WHERE player_name = 'aName',
SELECT date_id FROM `Date` WHERE date_value LIKE '12122015'
```
|
mysql: Insert with values from another table
|
[
"",
"mysql",
"sql",
"insert",
"dml",
""
] |
**Table1:**
id | car1 | car2 | car3 | car4
```
**Table2:**
id | windows | doors | engines
```
I have this sql code:
```
sum(car1) + sum(car2) + sum(car3) + sum(car4) as 'tot_cars',
sum('doors') as 'tot_doors'
'tot_doors' - 'tot_cars' as 'door_rest'
```
I've tried this also and not working:
```
sum(car1) + sum(car2) + sum(car3) + sum(car4) as 'tot_cars',
sum('doors') as 'tot_doors'
('tot_doors' - 'tot_cars' as 'door_rest')
```
This:
```
sum(car1) + sum(car2) + sum(car3) + sum(car4) as 'tot_cars',
sum('doors') as 'tot_doors'
('tot_doors - tot_cars as door_rest')
```
And this:
```
sum(car1) + sum(car2) + sum(car3) + sum(car4) as 'tot_cars',
sum('doors') as 'tot_doors'
('tot_doors - tot_cars') as 'door_rest'
```
All not working.
Still I'm having errors in SQLSyntax, it said cannot find '***door\_rest***' field in the database.
There are no problem with joining the two tables, because when I was querying the '***tot\_cars***' it showed the data on my page. But I'm having trouble with the '***door\_rest***' field.
Thank you for the help.
|
Do not use single quotes for column aliases. The value of:
```
sum('doors')
```
is 0, because it is summing the string `'doors'`. And, MySQL converts strings to integers based on leading digits -- which results in 0 in this case. Only escape names that need to be escaped, to avoid extra typing and make your queries more clear. Use the proper escape character (a backtick). And then choose names that don't need to be escaped.
Your problem is that you cannot use an alias in the same select, so:
```
sum(car1) + sum(car2) + sum(car3) + sum(car4) as tot_cars,
sum(doors) as tot_doors,
(sum(car1) + sum(car2) + sum(car3) + sum(car4) - sum(doors)) as door_rest
```
|
Aliases are not available on the SELECT clause, so you have to repeat the sum:
```
select
sum(car1) + sum(car2) + sum(car3) + sum(car4) as tot_cars,
sum(doors) as tot_doors,
sum(doors) - sum(car1) - sum(car2) - sum(car3) - sum(car4) as door_rest
```
also you can just use one sum function for each calculated field (unless you have null values, but you have to fix your original query anyway if there are some null values):
```
select
sum(car1 + car2 + car3 + car4) as tot_cars,
sum(doors) as tot_doors,
sum(doors - car1 - car2 - car3 - car4) as door_rest
```
|
Simple Sum and Subtract Syntax Error
|
[
"",
"mysql",
"sql",
"codeigniter",
""
] |
I'm working in a fault-reporting Oracle database, trying to get fault information out of it.
The main table I'm querying is Incident, which includes incident information. Each record in Incident may have any number of records in the WorkOrder table (or none) and each record in WorkOrder may have any number of records in the WorkLog table (or none).
What I am trying to do at this point is, for each record in Incident, find the WorkLog with the minimum value in the field MXRONSITE, and, for that worklog, return the MXRONSITE time and the REPORTDATE from the work order. I accomplished this using a MIN subquery, but it turned out that several worklogs could have the same MXRONSITE time, so I was pulling back more records than I wanted. I tried to create a subsubquery for it, but it now says I have an invalid identifier (ORA-00904) for WOL1.WONUM in the WHERE line, even though that identifier is in use elsewhere.
Any help is appreciated. Note that there is other stuff in the query, but the rest of the query works in isolation, and this but doesn't work in the full query or on its own.
```
SELECT
WL1.MXRONSITE as "Date_First_Onsite",
WOL1.REPORTDATE as "Date_First_Onsite_Notified"
FROM Maximo.Incident
LEFT JOIN (Maximo.WorkOrder WOL1
LEFT JOIN Maximo.Worklog WL1
ON WL1.RECORDKEY = WOL1.WONUM)
ON WOL1.ORIGRECORDID = Incident.TICKETID
AND WOL1.ORIGRECORDCLASS = 'INCIDENT'
WHERE (WL1.WORKLOGID IN
(SELECT MIN(WL3.WORKLOGID)
FROM (SELECT MIN(WL3.MXRONSITE), WL3.WORKLOGID
FROM Maximo.Worklog WL3 WHERE WOL1.WONUM = WL3.RECORDKEY))
or WL1.WORKLOGID is null)
```
To clarify, what I want is:
* For each fault in Incident,
* the earliest MXRONSITE from the Worklog table (if such a value exists),
* For that worklog, information from the associated record from the WorkOrder table.
This is complicated by Incident records having multiple work orders, and work orders having multiple work logs, which may have the same MXRONSITE time.
---
After some trials, I have found an (almost) working solution:
```
WITH WLONSITE as (
SELECT
MIN(WLW.MXRONSITE) as "ONSITE",
WLWOW.ORIGRECORDID as "TICKETID",
WLWOW.WONUM as "WONUM"
FROM
MAXIMO.WORKLOG WLW
INNER JOIN
MAXIMO.WORKORDER WLWOW
ON
WLW.RECORDKEY = WLWOW.WONUM
WHERE
WLWOW.ORIGRECORDCLASS = 'INCIDENT'
GROUP BY
WLWOW.ORIGRECORDID, WLWOW.WONUM
)
select
incident.ticketid,
wlonsite.onsite,
wlonsite.wonum
from
maximo.incident
LEFT JOIN WLONSITE
ON WLONSITE.TICKETID = Incident.TICKETID
WHERE
(WLONSITE.ONSITE is null or WLONSITE.ONSITE = (SELECT MIN(WLONSITE.ONSITE) FROM WLONSITE WHERE WLONSITE.TICKETID = Incident.TICKETID AND ROWNUM=1))
AND Incident.AFFECTEDDATE >= TO_DATE ('01/12/2015', 'DD/MM/YYYY')
```
This however is significantly slower, and also still not quite right, as it turns out a single Incident can have multiple Work Orders with the same ONSITE time (aaargh!).
---
As requested, here is a sample input, and what I want to get from it (apologies for the formatting). Note that while TICKETID and WONUM are primary keys, they are strings rather than integers. WORKLOGID is an integer.
Incident table:
TICKETID / Description / FieldX
1 / WORD1 / S
2 / WORD2 / P
3 / WORDX /
4 / / Q
Work order table:
WONUM / ORIGRECORDID / REPORTDATE
11 / 1 / 2015-01-01
12 / 2 / 2015-01-01
13 / 2 / 2015-02-04
14 / 3 / 2015-04-05
Worklog table:
WORKLOGID / RECORDKEY / MXRONSITE
101 / 11 / 2015-01-05
102 / 12 / 2015-01-04
103 / 12 /
104 / 12 / 2015-02-05
105 / 13 /
Output:
TICKETID / WONUM / WORKLOGID
1 / 11 / 101
2 / 12 / 102
3 / /
4 / /
(Worklog 101 linked to TICKETID 1, has non-null MXRONSITE, and is from work order 11)
(Worklogs 102-105 linked to TICKETID 2, of which 102 has lowest MXRONSITE, and is work order 12)
(No work logs associated with faults 103 or 104, so work order and worklog fields are null)
---
Post Christmas attack!
I have found a solution which works:
The method I found was to use multiple WITH queries, as follows:
```
WLMINL AS (
SELECT
RECORDKEY, MXRONSITE, MIN(WORKLOGID) AS "WORKLOG"
FROM MAXIMO.WORKLOG
WHERE WORKLOG.CLASS = 'WORKORDER'
GROUP BY RECORDKEY, MXRONSITE
),
WLMIND AS (
SELECT
RECORDKEY, MIN(MXRONSITE) AS "MXRONSITE"
FROM MAXIMO.WORKLOG
WHERE WORKLOG.CLASS = 'WORKORDER'
GROUP BY RECORDKEY
),
WLMIN AS (
SELECT
WLMIND.RECORDKEY AS "WONUM", WLMIND.MXRONSITE AS "ONSITE", WLMINL.WORKLOG AS "WORKLOGID"
FROM
WLMIND
INNER JOIN
WLMINL
ON
WLMIND.RECORDKEY = WLMINL.RECORDKEY AND WLMIND.MXRONSITE = WLMINL.MXRONSITE
)
```
Thus for each work order finding the first date, then for each work order and date finding the lowest worklogid, then joining the two tables. This is then repeated at a higher level to find the data by incident.
However this method does not work in a reasonable time, so while it may be suitable for smaller databases it's no good for the behemoths I'm working with.
|
I would do this with `row_number` function:
[SQLFiddle](http://sqlfiddle.com/#!4/1ec4f/1)
```
select ticketid, case when worklogid is not null then reportdate end d1, mxronsite d2
from (
select i.ticketid, wo.reportdate, wl.mxronsite, wo.wonum, wl.worklogid,
row_number() over (partition by i.ticketid
order by wl.mxronsite, wo.reportdate) rn
from incident i
left join workorder wo on wo.origrecordid = i.ticketid
and wo.origrecordclass = 'INCIDENT'
left join worklog wl on wl.recordkey = wo.wonum )
where rn = 1 order by ticketid
```
|
I may not have the details right on what you're trying to do... if you have some sample input and desired output, that would be a big help.
That said, I think an analytic function would help a lot, not only in getting the output but in organizing the code. Here is an example of how the `max` analytic function in a subquery could be used.
Again, the details on the join may be off -- if you can furnish some sample input and output, I'll bet someone can get to where you're trying to go:
```
with wo as (
select
wonum, origrecordclass, origrecordid, reportdate,
max (reportdate) over (partition by origrecordid) as max_date
from Maximo.workorder
where origrecordclass = 'INCIDENT'
),
logs as (
select
worklogid, mxronsite, recordkey,
max (mxronsite) over (partition by recordkey) as max_mx
from Maximo.worklog
)
select
i.ticketid,
l.mxronsite as "Date_First_Onsite",
wo.reportdate as "Date_First_Onsite_Notified"
from
Maximo.incident i
left join wo on
wo.origrecordid = i.ticketid and
wo.reportdate = wo.max_date
left join logs l on
wo.wonum = l.recordkey and
l.mxronsite = l.max_mx
```
-- edit --
Based on your sample input and desired output, this appears to give the desired result. It does do somewhat of an explosion in the subquery, but hopefully the efficiency of the analytic functions will dampen that. They are typically much faster, compared to using group by:
```
with wo_logs as (
select
wo.wonum, wo.origrecordclass, wo.origrecordid, wo.reportdate,
l.worklogid, l.mxronsite, l.recordkey,
max (reportdate) over (partition by origrecordid) as max_date,
min (mxronsite) over (partition by recordkey) as min_mx
from
Maximo.workorder wo
left join Maximo.worklog l on wo.wonum = l.recordkey
where wo.origrecordclass = 'INCIDENT'
)
select
i.ticketid, wl.wonum, wl.worklogid,
wl.mxronsite as "Date_First_Onsite",
wl.reportdate as "Date_First_Onsite_Notified"
from
Maximo.incident i
left join wo_logs wl on
i.ticketid = wl.origrecordid and
wl.mxronsite = wl.min_mx
order by 1
```
|
ORA-00904 "invalid identifier" but identifier exists in query
|
[
"",
"sql",
"oracle",
"identifier",
""
] |
Let's say I have a database with N tables (30-50) with different data. All tables have column "CreatedDate"
So, I want to select last 100 records from database based on this date for all tables for log/audit purposes.
One way is to do `union all` on all tables manually. Or use stored procedure along with `sys.tables`
But I thought there's a better way to see a convenient list of all records inserted in sql server.
Maybe there's a built-in or 3rd party tool for it as well.
|
I guess thos top 100 rowas may be from just one of the tables hence the TOP 100 for each table.
But with below, I believe you just need to write the function "FunctionToGetAllColumnsForTableIntoOneBigOne()" whcich you should be able to do with the other link I supplied.....
```
DECLARE @dt DateTime = GetDate();
DECLARE @sqlCommand NVARCHAR(MAX);
DECLARE @tmpsqlCommand NVARCHAR(100);
DECLARE curTbls CURSOR FOR SELECT 'SELECT TOP 100 CreatedDate, ' + FunctionToGetAllColumnsForTableIntoOneBigOne(name) as colMain + ' FROM ' + name + ' UNION ALL ' FROM Sys.tables;
OPEN curTbls
FETCH NEXT FROM curTbls
INTO @sqlCommand;
WHILE @@FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM curTbls
INTO @tmpsqlCommand;
SET @sqlCommand = @sqlCommand + @tmpsqlCommand;
END;
CLOSE curTbls;
DEALLOCATE curTbls;
SET @sqlCommand = @sqlCommand + ' SELECT GetDate(),'
SET @sqlCommand = 'SELECT TOP 100 * FROM ( '+ @sqlCommand + ') sub_q ORDER BY CreatedDate DESC'
--SELECT @sqlCommand
EXECUTE sp_executesql @sqlCommand
```
Good luck - I do hope this is of some assistance.
|
You can use dynamic SQL ... hope this helps
```
DECLARE @sql NVARCHAR(MAX) = N'';
SELECT @sql += N'
SELECT TOP (100) *
FROM ' + QUOTENAME(SCHEMA_NAME([schema_id]))
+ '.' + QUOTENAME(name)
+ '
ORDER BY CreatedDate DESC'';'
FROM sys.tables AS t;
PRINT @sql;
EXEC sp_executesql @sql;
```
OR
Wrap around dynamic SQL and this should help you
```
SELECT 'Select Top 100 * From ' + SCHEMA_NAME(schema_id) + '.' + name +'
ORDER BY CreatedOn DESC'
FROM sys.objects
WHERE TYPE = 'U'
```
OR
```
EXEC sp_MSforeachtable 'select top(100) * from ?'
```
|
How to display last 100 rows from all tables across database
|
[
"",
"sql",
"sql-server",
""
] |
## Desired result :
Have an accent sensitive primary key in MySQL.
I have a table of unique words, so I use the word itself as a primary key (by the way if someone can give me an advice about it, I have no idea if it's a good design/practice or not).
I need that field to be accent (and why not case) sensitive, because it must distinguish between, for instance, `'demandé'` and `'demande'`, two different inflexions of the French verb "demander". I do not have any problem to store accented words in the database. I just can't insert two accented characters strings that are identical when unaccented.
## Error :
When trying to create the `'demandé'` row with the following query:
```
INSERT INTO `corpus`.`token` (`name_token`) VALUES ('demandé');
```
I got this error :
```
ERROR 1062: 1062: Duplicate entry 'demandé' for key 'PRIMARY'
```
## Questions :
* Where in the process should a make a modification in order to have two different unique primary keys for "demande" and "demandé" in that table ?
**SOLUTION** [using 'collate utf8\_general\_ci'](https://stackoverflow.com/a/34388168/5419761) in table declaration
* How can i make accent sensitive queries ? Is the following the right way :
`SELECT * FROM corpus.token WHERE name_token = 'demandé' COLLATE utf8_bin`
**SOLUTION** [using 'collate utf8\_bin'](https://stackoverflow.com/a/34388015/5419761) with WHERE statement
* I found that i can achieve this point by using the `BINARY` Keyword (see this [sqlFiddle](http://www.sqlfiddle.com/#!9/99787/1)). What is the difference between `collate` and `binary`?
* Can I preserve other tables from any changes ? (I'll have to rebuild that table anyway, because it's kind of messy)
* I'm not very comfortable with encoding in MySQL. I don't have any problem yet with encoding in that database (and I'm kind of lucky because my data might not always use the same encoding... and there is not much I can do about it). I have a feeling that any modification regarding to that "accent sensitive" issue might create some encoding issue with other queries or data integrity. Am I right to be concerned?
## Step by step :
Database creation :
```
CREATE DATABASE corpus DEFAULT CHARACTER SET utf8;
```
Table of unique words :
```
CREATE TABLE token (name_token VARCHAR(50), freq INTEGER, CONSTRAINT pk_token PRIMARY KEY (name_token))
```
Queries
```
SELECT * FROM corpus.token WHERE name_token = 'demande';
SELECT * FROM corpus.token WHERE name_token = 'demandé';
```
both returns the same row:
```
demande
```
|
**Collations**. You have two choices, not three:
`utf8_bin` treats all of these as *different*: `demandé` and `demande` and `Demandé`.
`utf8_..._ci` (typically `utf8_general_ci` or `utf8_unicode_ci`) treats all of these as the *same*: `demandé` and `demande` and `Demandé`.
If you want only case sensitivity (`demandé` = `demande`, but neither match `Demandé`), you are out of luck.
If you want only accent sensitivity (`demandé` = `Demandé`, but neither match `demande`), you are out of luck.
**Declaration**. The best way to do whatever you pick:
```
CREATE TABLE (
name VARCHAR(...) CHARACTER SET utf8 COLLATE utf8_... NOT NULL,
...
PRIMARY KEY(name)
)
```
**Don't change collation on the fly**. This won't use the index (that is, will be slow) if the collation is different in `name`:
```
WHERE name = ... COLLATE ...
```
**BINARY**. The *datatypes* `BINARY`, `VARBINARY` and `BLOB` are very much like `CHAR`, `VARCHAR`, and `TEXT` with `COLLATE ..._bin`. Perhaps the only difference is that text will be checked for valid utf8 storing in a `VARCHAR ... COLLATE ..._bin`, but it will not be checked when storing into `VARBINARY...`. *Comparisons* (`WHERE`, `ORDER BY`, etc) will be the same; that is, simply compare the bits, don't do case folding or accent stripping, etc.
|
May be you need this
\_ci in a collation name=case insensitive
If your searches on that field are always going to be case-sensitive, then declare the collation of the field as utf8\_bin... that'll compare for equality the utf8-encoded bytes.
`col_name varchar(10) collate utf8_bin`
If searches are normally case-insensitive, but you want to make an exception for this search, try;
`WHERE col_name = 'demandé' collate utf8_bin`
[More here](http://dev.mysql.com/doc/refman/5.6/en/charset-collation-implementations.html)
|
Use accent sensitive primary key in MySQL
|
[
"",
"mysql",
"sql",
"encoding",
"primary-key",
"diacritics",
""
] |
I have 3 tables like this:
```
CREATE table materials
(id serial primary key not null,
name varchar(50) not null,
unit varchar(10) not null default 'шт',
price decimal(12, 2) not null check (price>0));
CREATE table warehouses
(id serial primary key not null,
lastname varchar(25) not null);
CREATE table materials_in_warehouses
(id_warehouses integer references warehouses(id) on update cascade on delete cascade,
id_materials integer references materials(id),
unit varchar(15) default 'шт',
count integer not null CHECK (count>0),
lastdate date not null,
primary key (id_warehouses, id_materials);
```
I need to select all materials with the price of > 200 , such that:
on each warehouse this material is available in an amount of > 100.
The problem is that the condition we have to fit all the warehouses with this material, not any one. I have no ideas.
For example, i have:
```
materials
id name price unit
--- ------ ----- -----
3 Silver 300 kg
warehouses
id lastname
---- ---------
2 Forman
3 Tramp
materials_in_warehouses
id_materials id_warehouses count lastdate
------------ ------------- ----- --------
3 3 300 2015-12-20
3 2 200 2015-12-20
```
...and i want to see Silver in my result, but if i add to table materials\_in\_warehouses where count was < 100, as a result, silver should not be.
This is my example query, but it is not suitable for the condition
```
select materials.name
, materials.price
, materials.unit
from materials
, materials_in_warehouses
where price > 200
AND id = id_materials
AND count > 100;
```
|
You can solve this with subqueries like this:
First case, count > 100 at each warehouse
```
SELECT * FROM materials WHERE id IN (
SELECT m.id FROM
materials_in_warehouses AS mw INNER JOIN
materials AS m ON (m.id = mw.id_materials)
WHERE
m.price > 200 AND
mw.count > 100
GROUP BY id
HAVING COUNT(*) = (SELECT COUNT(*) FROM warehouses)
);
```
Second case, sum of all warehouse count > 100
```
SELECT * FROM materials WHERE id IN (
SELECT m.id FROM
materials_in_warehouses AS mw INNER JOIN
materials AS m ON (m.id = mw.id_materials)
WHERE
m.price > 200
GROUP BY id
HAVING SUM(mw.count) > 100
);
```
OK, third case, all materials where price > 200 **AND** count in each warehouse > 100
```
SELECT m.* FROM
materials_in_warehouses AS mw INNER JOIN
materials AS m ON (m.id = mw.id_materials)
WHERE
m.price > 200 AND
mw.count > 100
GROUP BY id
```
As simple as possible
|
You will need to firstly JOIN the tables and establish the relationships.
```
SELECT
w.lastname
, m.name
, m.price
, miw.count
FROM materials m
INNER JOIN materials_in_warehouses miw
ON m.id = miw.id_materials
INNER JOIN warehouses w
ON w.id = miw.id_warehouses
```
From there, you can add where clauses to locate the data you wish.
```
WHERE m.price >= 200
AND miw.count > 100
```
An ORDER would help as well, but only to view the results.
```
ORDER BY w.lastname, m.name
```
If you are still missing records you expect to see at this point, its likely a data problem (you dont have warehouses defined in the MIW table, or materials are missing from the materials table).
EDIT: If you consider the data in the above question, and add change the MIW row for warehouse 2 to have a count of 50, then that row will be excluded. You will still see Silver listed in the results because it exists at warehouse 3 in the quantity you seek.
|
Postgresql no ideas to select query
|
[
"",
"sql",
"postgresql",
"select",
""
] |
I have two tables: one is foreign reference table lets say ***table a*** and other one is the data table lets say ***table b***.
Now, when I need to change the data in ***table b***, but I get restricted by ***table a***.
How can I change "rid" in both tables without getting this message?
> "ERROR: insert or update on table "table a" violates foreign key
> constraint "fk\_boo\_kid" SQL state: 23503
Detail: Key (kid)=(110) is not present in table "table b".
Example query to update both tables:
```
UPDATE table b table a SET rid = 110 WHERE rid =1
```
```
table b
+-----+-------+-------+
| rid | ride | qunta |
+-----+-------+-------+
| 1 | car | 1 |
| 2 | bike | 1 |
+-----+-------+-------+
table a
+-----+-----+------------+
| kid | rid | date |
+-----+-----+------------+
| 1 | 1 | 20-12-2015 |
| 2 | 2 | 20-12-2015 |
+-----+-----+------------+
```
|
In Postgres you can use a writeable CTE to update both tables in a single statement.
Assuming this table setup:
```
create table a (rid integer primary key, ride text, qunta integer);
create table b (kid integer primary key, rid integer references a, date date);
```
The CTE would be:
```
with new_a as (
update a
set rid = 110
where rid = 1
)
update b
set rid = 110
where rid = 1;
```
As (non-deferrable) foreign keys are evaluated on statement level and both the primary and foreign key are changed in the same *statement*, this works.
SQLFiddle: <http://sqlfiddle.com/#!15/db6d1/1>
|
you can not update/delete primary key in table B, because the primary key is used in table A.
you can delete primary key in table B, IF >>
1. you must delete the row in table A which is used primary key table B.
2. you can delete the row in table B
|
How to update rows of two tables that have foreign key restrictions
|
[
"",
"sql",
"postgresql",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.