Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have two tables:
```
Membership
mID StartingDate Name Address Gender EndingDate
```
And
```
Circulation Info
ISBN mID DateOfBorrow DateOfReturn DateOfLoss
```
I am attempting to find the activity level of each genders, but as of right now I am not having ver much luck.
Here is what I have tried so far:
```
SELECT Membership.Gender, [Circulation Info].mID, Membership.mID
FROM [Circulation Info] AS c INNER JOIN Membership AS m ON [Circulation Info].mID = Membership.mID
GROUP BY m.mID
HAVING Membership.Gender='F'
```
I receive a syntax error when I attempt to run this and it directs me to Circulation Info on the first line. | In addition to the issue about the table aliases (when you alias a table, you must then use that alias rather than the table name to qualify the field names), I think you want a `Count()` function to give you "activity level".
Also note Access generally complains about any field expression in the `SELECT` clause which is not included in the `GROUP BY` and is not an aggregate expression (`Min()`, `Max()`, `Count()`, etc.).
I don't see why you should need both `c.mID` and `m.mID` in the `SELECT` list; they should be the same in each row. Also consider moving the criterion, `m.Gender='F'`, from the `HAVING` to a `WHERE` clause.
```
SELECT m.mID, Count(*) AS activity_level
FROM
[Circulation Info] AS c
INNER JOIN Membership AS m
ON c.mID = m.mID
WHERE m.Gender='F'
GROUP BY m.mID;
``` | The reason is that you have set an alias for tables, but then use table name prefixing column names instead of alias. Try this:
```
SELECT m.Gender, c.mID, m.mID
FROM [Circulation Info] AS c INNER JOIN Membership AS m ON c.mID = m.mID
GROUP BY m.mID
HAVING m.Gender='F';
``` | Finding Activity level of gender | [
"",
"sql",
"ms-access",
""
] |
I'm looking to create three separate check constraints for my SQL Server database to ensure that a password field constrains a minimum of one number, one uppercase character and one special character.
I consider the best way to approach is by creating separate check constrains for example I have created the following constraint to ensure that password length is a minimum of 8
`(len([password]) <= (8))`
Could any one suggest a way to establish the required validation.
Thanks | You can do this with one constraint, something like:
```
check password like '%[0-9]%' and password like '%[A-Z]%' and password like '%[!@#$%a^&*()-_+=.,;:'"`~]%' and len(password) >= 8
```
Just a note about the upper case comparison: this requires that the collation being used be case sensitive. You may need to specify an explicit `COLLATE` in the comparison to be sure that it is case sensitive. | I did not know answer for your question directly, but after some research i found this methods:
1) Check if given string contains uppercase character
```
SELECT CASE WHEN BINARY_CHECKSUM([password]) = BINARY_CHECKSUM(LOWER([password])) THEN 0 ELSE 1 END AS DoesContainUpperCase
GO
```
source: <http://www.sqlservercentral.com/Forums/Topic800271-338-1.aspx>
2) Check if given string contains at least one special character
We can make simply statement
```
IF ([password] LIKE '%[^a-zA-Z0-9]%')
```
source: [How to detect if a string contains special characters?](https://stackoverflow.com/questions/2558755/how-to-detect-if-a-string-contains-special-characters)
I hope my answer helped you.
Kind regards,
Rafal | Check Constraint- Check password contains atleast one number/special Character/uppercase | [
"",
"sql",
"sql-server",
"check-constraint",
""
] |
I've been working with tsql for quite a while now but I've never seen binary anding or oring in WHERE clause. Now I'm developing new application that would benefit from applying a bitmask.
Lets say I have 16 product grades. Each grade is representrd by a bit position in a bit[] column. So grade A109 would be 0000000000000001, grade B704 would be 0000001000000000, grade V64 is 0100000000000000 and so on. Any grade can only have single 1 in its array column. Now let's say I can turn each of those 3 grades into one another in manufacturing process. So my bit mask for this search would be 0100001000000001. How would I write a WHERE clause to list items of all those 3 grades? | I did some more research and the best solution is to compare masks with bitwise AND operator like this
```
WHERE mask1 & mask2 <> 0
```
This is easy, simple and cohesive. | First time for me too. Interesting.
```
declare @A109 int = 1;
declare @B704 int = 512;
declare @V64 int = 16384;
declare @Xx int = 32;
declare @mask int = 16897; --@A109+@B704+@V64
create table #MyData (
name char(2),
value int);
insert #MyData
values ('a', @A109), ('b1', @B704), ('b2',@B704), ('c', @Xx);
select
name,
value
from #MyData
where (value & @mask) in (@A109, @B704, @V64);
drop table #MyData;
```
It seems you can't do bitwise operations on binary data! ["In a bitwise operation, only one expression can be of either binary or varbinary data type"](http://technet.microsoft.com/en-us/library/ms174965%28v=sql.105%29.aspx). | comparing bit array to bit mask in tsql | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
```
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["techconn"].ToString());
SqlCommand com = new SqlCommand("select * from hs where ac between'" + TextBox1.Text + "'and '" + TextBox2.Text + "' and em='" + DropDownList1.SelectedItem.Text.ToString() + "'", con);
DataTable dt = new DataTable();
con.Open();
SqlDataAdapter sqlDa = new SqlDataAdapter(com);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
else
{
GridView1.Visible = false;
}
con.Close();
```
Is this code safe from SQL injection?
If not, please correct this code that it is safe from SQL injection.
I am using SQL Server 2008. | In short, the answer is no. You need to always use parameters in your queries.
```
SqlCommand com = new SqlCommand("select * from hs where ac between @ac1 and @ac2 and em=@em", con);
```
You then add the parameters to your SqlCommand object (com). | Yes your code is quite prone to issues, not only sql injection attacks. Try the following:
```
public DataTable GetData(string textbox1, string textbox2, string dropdown)
{
DataTable result = null;
string connString = null;
if (ConfigurationManager.ConnectionStrings["techconn"] != null)
connString = ConfigurationManager.ConnectionStrings["techconn"].ConnectionString;
if (!string.IsNullOrEmpty(connString))
using (SqlConnection con = new SqlConnection(connString))
{
con.Open();
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "select * from hs where (ac between @a and @b) and em = @c";
cmd.Parameters.AddWithValue("@a", textbox1);
cmd.Parameters.AddWithValue("@b", textbox2);
cmd.Parameters.AddWithValue("@c", dropdown);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
result = new DataTable();
da.Fill(result);
}
}
}
return result;
}
```
Paste it in your code and use by
```
DataTable dt = GetData(TextBox1.Text, TextBox2.Text, DropDownList1.SelectedItem.Text.ToString());
if (dt != null && dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
else
{
GridView1.Visible = false;
}
```
Test it properly too. | Safety from SQL injection | [
"",
"sql",
"sql-server",
"c#-4.0",
"sql-injection",
""
] |
I have two tables with
```
table 1
col1 date
1 13/4/2014
2 15/4/2014
3 17/4/2014
5 19/4/2014
table 2
col1 date
1 13/4/2014
3 16/4/2014
6 18/4/2014
joining the two tables i should get
col1 date col2 date
1 13/4/2014 1 13/4/2014
2 15/4/2014
3 17/4/2014 3 16/4/2014
6 18/4/2014
5 19/4/2014
```
the important thing is the `date` columns should be sorted as can be seen for `col` data `6` and `5`.
Is this possible?
EDIT :
the final table needs to be ordered by `col1.date` and `col2.date` such that earlier date either in `col1` or `col2` will be sorted in the join table `18/4/2014` will come before `19/4/2014` even if they are in different columns. I hope i am making my point clear.
Thanks
EDIT :
```
table 1
1, "2014-04-03"
2, "2014-04-04"
3, "2014-04-11"
4, "2014-04-16"
5, "2014-04-04"
6, "2014-04-17"
7, "2014-04-17"
table 2
1, "2014-04-04"
2, "2014-04-11"
5, "2014-04-17"
```
EDIT : after join it should be like
```
1 2014-04-03
2 2014-04-04
5 2014-04-04 1 2014-04-04
3 2014-04-11 2 2014-04-11
4 2014-04-16
6 2014-04-17
7 2014-04-17 5 2014-04-17
``` | ```
select n.col1
, n.date1
, m.col2
, m.date2
from t1 n
full join t2 m on n.date1 = m.date2
and n.col1 = (select max(col1) from t1 where date1 = m.date2 )
and n.col1 is not null
where n.date1 is not null or m.date2 is not null
order by coalesce(n.date1, m.date2)
, coalesce(n.col1, m.col2)
```
[**SQLFiddle with new data**](http://sqlfiddle.com/#!15/9a646/69)
[**SQLFiddle with old data**](http://sqlfiddle.com/#!15/3d2c4/62) | [SQL Fiddle](http://sqlfiddle.com/#!15/3d2c4/2)
```
select col1, date1, col2, date2
from
t1
full outer join
t2 on col1 = col2
order by coalesce(date1, date2), date2;
``` | SQL joins with order by | [
"",
"sql",
"postgresql",
"join",
"postgresql-9.1",
""
] |
I have the following tables:
```
sh_feeds
=> id
=> feed_id
sh_subscriptions
=> id
=> user_id
=> feed_id
```
The query I'm trying to produce is:
> Select all from `sh_feeds` where `feed_id` matches a `feed_id` in
> `sh_subscriptions` which corresponds to a `user_id` that matches
> `$user_id`.
Slightly confusing, but hopefully that's clear enough.
I know there's going to be a lot of joining, and I've refreshed my memory with [this explainer](http://www.sitepoint.com/understanding-sql-joins-mysql-database/), but I still can't seem to make it work. | Should be fairly easy, like this:
The inner join ensures that only rows are included for which the feed\_id also occurs in sh\_subscriptions.
```
SELECT f.* FROM sh_feeds f
INNER JOIN sh_subscriptions s ON f.feed_id = s.feed_id
WHERE s.user_id = $user_id;
``` | Try this
```
SELECT * FROM sh_feeds F
INNER JOIN sh_subscriptions S ON F.feed_id = S.feed_id
WHERE S.user_id = $user_id;
``` | How would I express this MySQL JOINs query? | [
"",
"mysql",
"sql",
"join",
""
] |
should be simple one but i am currently really confused
i have a db query :
```
public double markingAvg(Marking id) {
System.out.println("In MarkingAvg");
System.out.println("id = " + id);
System.out.println("id = " + id.getId());
Query m = em.createQuery("SELECT m.markSectionOne, m.markSectionTwo, m.markSectionThree, m.markSectionFour, m.markSectionFive, m.markSectionSix, m.markSectionSeven, m.markSectionEight, m.markSectionNine, m.markSectionTen, m.markSectionEleven, m.markSectionTwelve, m.markSectionThirteen FROM MARKING m WHERE m.id = :id", Double.class);
m.setParameter("id", id.getId()); // Note the getId()
System.out.println(m);
List<Object[]> allMarks = m.getResultList();
double total = 0.0;
int count = 0;
for (Object[] marks : allMarks) {
for (Object mark : marks) {
total += Double.parseDouble((String) mark);
++count;
}
}
return total / (double) count;
}
```
which just gets the values from the 13 columns and does the average on them, however it breaks when there is a null value in them, is there any way to say if there is a null value from any of the columns to return the total to be 0? Thanks | You could use inline conditional check for this:
```
total += Double.parseDouble((String) ((mark==null) ? 0 : mark)));
``` | You could also handle this in your query: E.g.:
```
ij> CREATE TABLE T(I INT);
ij> INSERT INTO T VALUES 1, 2, 3, NULL;
4 rows inserted/updated/deleted
ij> SELECT * FROM T;
I
-----------
1
2
3
NULL
4 rows selected
ij> SELECT (CASE WHEN I IS NULL THEN 0 ELSE I END) FROM T;
1
-----------
1
2
3
0
4 rows selected
```
In your case it might be even better to calculate the average in SQL
```
ij> SELECT AVG(CAST(I AS DOUBLE)) AS AVERAGE FROM T;
AVERAGE
------------------------
2.0
WARNING 01003: Null values were eliminated from the argument of a column function.
1 row selected
```
Note the warning. If you actually want the NULLs to count as 0 in the average you have to use the CASE expression mentioned above. | How to deal with null values - JPA/SQL/JPQL | [
"",
"sql",
"jpa",
"derby",
"jpql",
""
] |
I'm creating a database for a hypothetical video rental store.
All I need to do is a procedure that check the availabilty of a specific movie (obviously the movie can have several copies). So I have to check if there is a copy available for the rent, and take the number of the copy (because it'll affect other trigger later..).
I already did everything with the cursors and it works very well actually, but I need (i.e. "must") to do it without using cursors but just using "pure sql" (i.e. queries).
I'll explain briefly the scheme of my DB:
The tables that this procedure is going to use are 3: 'Copia Film' (Movie Copy) , 'Include' (Includes) , 'Noleggio' (Rent).
> Copia Film Table has this attributes:
>
> * idCopia
> * Genere (FK references to Film)
> * Titolo (FK references to Film)
> * dataUscita (FK references to Film)
>
> Include Table:
>
> * idNoleggio (FK references to Noleggio. Means idRent)
> * idCopia (FK references to Copia film. Means idCopy)
>
> Noleggio Table:
>
> * idNoleggio (PK)
> * dataNoleggio (dateOfRent)
> * dataRestituzione (dateReturn)
> * dateRestituito (dateReturned)
> * CF (FK to Person)
> * Prezzo (price)
Every movie can have more than one copy.
Every copy can be available in two cases:
1. The copy ID is not present in the Include Table (that means that the specific copy has ever been rented)
2. The copy ID is present in the Include Table and the dataRestituito (dateReturned) is not null (that means that the specific copy has been rented but has already returned)
The query I've tried to do is the following and is not working at all:
```
SELECT COUNT(*)
FROM NOLEGGIO
WHERE dataNoleggio IS NOT NULL AND dataRestituito IS NOT NULL AND idNoleggio IN (
SELECT N.idNoleggio
FROM NOLEGGIO N JOIN INCLUDE I ON N.idNoleggio=I.idNoleggio
WHERE idCopia IN (
SELECT idCopia
FROM COPIA_FILM
WHERE titolo='Pulp Fiction')) -- Of course the title is just an example
```
Well, from the query above I can't figure if a copy of the movie selected is available or not AND I can't take the copy ID if a copy of the movie were available.
(If you want, I can paste the cursors lines that work properly)
------ USING THE 'WITH SOLUTION' ----
I modified a little bit your code to this
```
WITH film
as
(
SELECT idCopia,titolo
FROM COPIA_FILM
WHERE titolo = 'Pulp Fiction'
),
copy_info as
(
SELECT N.idNoleggio, N.dataNoleggio, N.dataRestituito, I.idCopia
FROM NOLEGGIO N JOIN INCLUDE I ON N.idNoleggio = I.idNoleggio
),
avl as
(
SELECT film.titolo, copy_info.idNoleggio, copy_info.dataNoleggio,
copy_film.dataRestituito,film.idCopia
FROM film LEFT OUTER JOIN copy_info
ON film.idCopia = copy_info.idCopia
)
SELECT COUNT(*),idCopia FROM avl
WHERE(dataRestituito IS NOT NULL OR idNoleggio IS NULL)
GROUP BY idCopia
```
As I said in the comment, this code works properly if I use it just in a query, but once I try to make a procedure from this, I got errors.
The problem is the final SELECT:
```
SELECT COUNT(*), idCopia INTO CNT,COPYFILM
FROM avl
WHERE (dataRestituito IS NOT NULL OR idNoleggio IS NULL)
GROUP BY idCopia
```
The error is:
ORA-01422: exact fetch returns more than requested number of rows
ORA-06512: at "VIDEO.PR\_AVAILABILITY", line 9.
So it seems the Into clause is wrong because obviously the query returns more rows. What can I do ? I need to take the Copy ID (even just the first one on the list of rows) without using cursors. | You can try this -
```
WITH film
as
(
SELECT idCopia, titolo
FROM COPIA_FILM
WHERE titolo='Pulp Fiction'
),
copy_info as
(
select N.idNoleggio, I.dataNoleggio , I.dataRestituito , I.idCopia
FROM NOLEGGIO N JOIN INCLUDE I ON N.idNoleggio=I.idNoleggio
),
avl as
(
select film.titolo, copy_info.idNoleggio, copy_info.dataNoleggio,
copy_info.dataRestituito
from film LEFT OUTER JOIN copy_info
ON film.idCopia = copy_info.idCopia
)
select * from avl
where (dataRestituito IS NOT NULL OR idNoleggio IS NULL);
``` | You should think in terms of sets, rather than records.
If you find the set of all the films that are out, you can exclude them from your stock, and the rest is rentable.
```
select copiafilm.* from @f copiafilm
left join
(
select idCopia from @r Noleggio
inner join @i include on Noleggio.idNoleggio = include.idNoleggio
where dateRestituito is null
) out
on copiafilm.idCopia = out.idCopia
where out.idCopia is null
``` | SQL Queries instead of Cursors | [
"",
"sql",
"database",
"oracle",
"cursor",
""
] |
I need to display some data in an SSRS 2008r2 report and the colors have to match a Windows VB app that saves it's colors as integers (e.g.16744703 is a pinkish color). I believe this is ARGB format. I'm not concerned about the alpha value, as the application does not allow the user to modify it.
I'm stuck on the SQL to convert ARGB to something compatible in SSRS. I need to do the translation in SQL as there are other factors that may override an objects color.
I can work with 3 ints for rgb or a hex value
Anyone got any idea how tot do this?
Regards
mark | Figured it out. Here's a function that returs either RGB() or Hex
```
-- Description: Converts ARGB to RGB(RR,GG,BB)
-- e.g. 16744703 returns RGB(255,128,255) or #FF80FF
CREATE FUNCTION [dbo].[ARGB2RGB]
(
@ARGB AS BIGINT
,@ColorType AS VARCHAR(1) -- 'H' = Hex, 'R' = RGB
)
RETURNS VARCHAR(16)
AS
BEGIN
DECLARE @Octet1 TINYINT
DECLARE @Octet2 TINYINT
DECLARE @Octet3 TINYINT
DECLARE @Octet4 TINYINT
DECLARE @RestOfColor BIGINT
SET @Octet1 = @ARGB / 16777216
SET @RestOfColor = @ARGB - ( @Octet1 * CAST(16777216 AS BIGINT) )
SET @Octet2 = @RestOfColor / 65536
SET @RestOfColor = @RestOfColor - ( @Octet2 * 65536 )
SET @Octet3 = @RestOfColor / 256
SET @Octet4 = @RestOfColor - ( @Octet3 * 256 )
RETURN
CASE @ColorType
WHEN 'R'
THEN 'RGB(' + CONVERT(VARCHAR, @Octet4) + ','
+ CONVERT(VARCHAR, @Octet3) + ',' + CONVERT(VARCHAR, @Octet2)
+ ')'
WHEN 'H'
THEN '#' + RIGHT(sys.fn_varbintohexstr(@Octet4), 2)
+ RIGHT(sys.fn_varbintohexstr(@Octet3), 2)
+ RIGHT(sys.fn_varbintohexstr(@Octet2), 2)
END
END
```
Hope someone else finds it useful
Regards
Mark | ```
create FUNCTION [dbo].[ConvertRGB]
(
@ARGB AS float
)
RETURNS @ReturnValue TABLE ( R TINYINT,B TINYINT, G TINYINT )
as
BEGIN
DECLARE @testvarbinary binary(4)
DECLARE @strRBG nvarchar(MAX)
set @testvarbinary = CONVERT(binary(4),@ARGB)
set @strRBG=( SELECT substring(sys.fn_varbintohexstr(@testvarbinary),5,6))
DECLARE @temp AS TABLE (hex char(6))
INSERT INTO @temp
VALUES (@strRBG)
DECLARE @strHex AS varchar(16)
SET @strHex = '0123456789abcdef' -- Assuming case-insensitive collation!
INSERT INTO @ReturnValue
( R,G,B )
SELECT 16 * (CHARINDEX(SUBSTRING(hex, 1, 1), @strHex) - 1) + (CHARINDEX(SUBSTRING(hex, 2, 1), @strHex) - 1)
,16 * (CHARINDEX(SUBSTRING(hex, 3, 1), @strHex) - 1) + (CHARINDEX(SUBSTRING(hex, 4, 1), @strHex) - 1)
,16 * (CHARINDEX(SUBSTRING(hex, 5, 1), @strHex) - 1) + (CHARINDEX(SUBSTRING(hex, 6, 1), @strHex) - 1)
FROM @temp
RETURN
END;
GO
--select * from [ConvertRGB](10592513)
``` | Getting RGB(R,G,B) from ARGB integer (SQL) | [
"",
"sql",
"hex",
"argb",
""
] |
I'm trying to write a query that returns true if the same idx exists in another table.
Here is what I want to do.
Two Tables:
```
User (user_idx, name)
Group (group_idx, user_idx)
```
Pseudo Query:
```
SELECT user_idx, name, (True(1)/False(0) value) as has_joined_group
FROM User
WHERE (Check if user_idx exists in Group table where group_idx is 3)
```
Can this be done using Mysql? If yes, how? | ```
SELECT u.user_idx, u.name, g.user_idx IS NOT NULL AS has_joined_group
FROM User AS u
LEFT JOIN Group AS g
ON g.user_idx = u.user_idx AND g.group_idx = 3
``` | ```
SELECT
u.user_idx,
u.name,
CASE WHEN g.user_idx IS NOT NULL AND g.group_idx = 3 THEN 1 ELSE 0 END AS has_joined_group
FROM
user u JOIN LEFT group g ON u.user_idx = g.user_idx
``` | Mysql Return true if idx exists in another table | [
"",
"mysql",
"sql",
""
] |
Using a university relation (students are advised by instructors in different departments, only one advisor per student but advisors can have zero to many advisees), I'm attempting to write a function that computes the total number of students being advised in a given department.
Here are the tables and columns for reference:
```
student(id,name,dept_name,tot_cred)
instructor(id,name,dept_name, salary)
advisor(s_id,i_id)
```
I already know how to use delimiter and such so no I don't need to be told how to write a function. I'm just having issues getting what I want from the select statement alone.
This is the best I've been able to come up with so far:
```
SELECT *
FROM advisor
RIGHT OUTER JOIN instructor
ON i_id=id
ORDER BY dept_name;
```
This statement yields:

Is there a way I can write an if statement or some other statement to delete all of the NULL entries and then use a count function (within the custom function I'll be writing) that will count the number of instances dept\_name occurs, resulting in the total number of advisees per department? | ```
SELECT i.dept_name, COUNT(a.s_id)
FROM Instructor i
LEFT JOIN advisor a ON i.id = a.i_id
GROUP BY i.dept_name;
```
This will include zeros for departments with no advisees. | If you are interested in the number of advised students per *student* department then:
```
SELECT s.dept_name, COUNT(a.s_id)
FROM student s
LEFT JOIN advisor a ON a.s_id=s.id
GROUP BY s.dept_name
```
OTOH, if you are interested in the number of advised students per *instructor* department then:
```
SELECT i.dept_name, COUNT(a.s_id)
FROM instructor i
LEFT JOIN advisor a ON a.i_id=i.id
GROUP BY i.dept_name
``` | SQL Am I using this join correctly? | [
"",
"mysql",
"sql",
""
] |
Guys I have three tables in SQL database. `tblTicketDetail`, `tblEngineer` and `tblTicket_Engineer` (a junction table for many-to-many relationship). What happens in my app is, when I generate a new ticket, the ticket is assigned to either one, two or three (max) engineers (thus the many-to-many relationship).
Following is the structure of tables :
**`tblTicketDetail`**
`+----------+---------------+--------+
| TicketID | Desc | Status |
+----------+---------------+--------+
| 1 | Description 1 | 1 |
| 2 | Description 2 | 0 |
| 3 | Description 3 | 1 |
+----------+---------------+--------+`
**`tblEngineer`**
`+------------+-------+
| EngineerID | Name |
+------------+-------+
| 1 | Tom |
| 2 | Harry |
| 3 | John |
+------------+-------+`
**`tblTicket_Engineer`**
`+----------+------------+
| TicketID | EngineerID |
+----------+------------+
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
| 2 | 1 |
| 3 | 1 |
| 3 | 2 |
+----------+------------+`
Now what I want to do is COUNT all `TicketID` which have the `status` of 1 and where the `EngineerID` should be specific (like for example 1).
I tried this query, but it generates two counts
```
SELECT (
SELECT COUNT(*) total
FROM tblTicketDetail WHERE Status = 1
) AS count1,
(
SELECT COUNT(*) total
FROM tblTicket_Engineer WHERE EngineerID = 1
) AS count2
```
In this case (where EngineerID = 1), the query should generate the count of 2. How should I go about doing that? | You need to create a join on your sub-query to get the ticket status and the sub-query should look like below:
```
SELECT COUNT(*) total
FROM tblTicket_Engineer
INNER JOIN tblTicketDetail ON tblTicketDetail.TicketID = tblTicket_Engineer.TicketID AND tblTicketDetail.Status = 1
WHERE tblTicket_Engineer.EngineerID = 1
``` | I think below code will help you
```
SELECT Count(*) FROM
tblTicket inner join tblTicket_Engineer on
(tblTicket.TicketID= tblTicket_Engineer.TicketID)
WHERE tblTicket.Status = '1'
AND tblTicket_Engineer.EngineerID = '1'
``` | How to use COUNT on two tables with WHERE clause | [
"",
"sql",
"count",
""
] |
```
if(isset($_POST['update_page']))
{
if($_POST['agent_name']=="" and $_POST['company_name']=="" and $_POST['email']=="")
{
$response = asort_form_error("All agent detail fields should be filled");
extract($_POST);
}
else
{
$sql = "UPDATE ".TBL_AGENT." SET agent_name = '$_POST[agent_name]' , company_name = '$_POST[company_name]' , email = '$_POST[email]' WHERE agent_id = '{$_GET['id']}'";
mysql_query($sql,$CN);
$sql_query = "UPDATE ".TBL_SUBSCRIPTION." SET renewal_date = ( UNIX_TIMESTAMP() + ( '$_POST[subscription_renewal]' * 86400 ) ) WHERE agent_id = '{$_GET['id']}'";
mysql_query($sql_query,$CN);
$response = asort_form_ok("Agent Details Successfully Updated");
header('Location: subscription.php');
}
unset($_POST);
}
```
I'm trying to update the records of my multiple database tables (`TBL_AGENT` and `TBL_SUBSCRIPTION`) using same agent\_id. Above two queries working fine. I want to write in single line. How to write those two `$sql` and `$sql_query` in single line ? | This should work:
```
"UPDATE ".TBL_AGENT."
JOIN ".TBL_SUBSCRIPTION." ON ".TBL_AGENT.".agent_id = ".TBL_SUBSCRIPTION.".agent_id
SET ".TBL_AGENT.".agent_name = '$_POST[agent_name]' , ".TBL_AGENT.".company_name = '$_POST[company_name]' , ".TBL_AGENT.".email = '$_POST[email]', ".TBL_SUBSCRIPTION.".renewal_date = ( UNIX_TIMESTAMP() + ( '$_POST[subscription_renewal]' * 86400 ) )
WHERE ".TBL_AGENT.".agent_id = '{$_GET['id']}';"
``` | Use a `JOIN`
```
UPDATE tbl_agent AS a
JOIN tbl_subsription AS s ON a.agent_id = s.agent_id
SET a.agent_name = '$_POST[agent_name]',
s.renewal_date = ( UNIX_TIMESTAMP() + ( '$_POST[subscription_renewal]' * 86400 ) )
WHERE a.agent_d = '{$_GET['id']}'
``` | update records of multiple tables using same id | [
"",
"mysql",
"sql",
"join",
"insert-update",
""
] |
I have a table like
```
Name Description EID Basecode
----- ----------- ---- ---------
name1 ssdad 1001 S2378797
name2 gfd 1002 S1164478
name3 gfdsffsdf 1003 R1165778
name4 ssdad 1004 M0007867
name5 gfd 1005 N7765111
name6 gfdsffsdf 1006 W5464111
name5 gfd 1005 N7765111
name6 gfdsffsdf 1006 A4000011
name6 gfdsffsdf 1006 W5464111
name10 ssdad 1001 2378797
name21 gfd 1002 1164478
name17 ssdad 1001 765
name81 gfd 1002 1167
```
How to retrieve rows, only if columns data starts with any letter other than **W** and **N** in **Basecode** column.
To retrieve like
```
Name Description EID Basecode
----- ----------- ---- ---------
name1 ssdad 1001 S2378797
name2 gfd 1002 S1164478
name3 gfdsffsdf 1003 R1165778
name4 ssdad 1004 M0007867
name6 gfdsffsdf 1006 A4000011
``` | You can use Left and In as another approach, for example:
```
SELECT t.Name, t.Description, t.EID, t.Basecode
FROM TheTable AS t
WHERE Not IsNumeric(Left(t.Basecode,1)) AND Left(t.Basecode,1) Not In ("W","N")
``` | For a query run from within the Access application itself you could use something like this:
```
SELECT * FROM YourTableName
WHERE Basecode LIKE '[a-m]*' OR Basecode LIKE '[o-v]*' OR Basecode LIKE '[x-z]*'
```
Edit: As HansUp points out, the above can be condensed to
```
SELECT * FROM YourTableName WHERE Basecode LIKE '[a-mo-vx-z]*'
``` | How to find whether a column values are starting with letter access sql | [
"",
"sql",
"ms-access",
""
] |
I am getting an error: ORA-01789: query block has incorrect number of result columns
when trying to create a table from data in 2 other tables. Please help, is this just a syntax error or am I combining the tables in the wrong way?
```
CREATE TABLE EMPDATA(ID, NAME, SALARY, DEPTNAME)
AS
SELECT e.employee_id, (e.first_name || e.last_name), e.salary
FROM employees e
UNION
SELECT d.department_name
FROM departments d;
``` | I think you want `JOIN` instead of `UNION`:
```
CREATE TABLE EMPDATA(ID, NAME, SALARY, DEPTNAME)
AS
SELECT e.employee_id, (e.first_name || e.last_name), e.salary, d.department_name
FROM employees e
JOIN departments d on(d.department_id = e.department_id);
``` | The number of coumns while using UNION should be same in the SELECT statement | Create table error oracle | [
"",
"sql",
"oracle",
""
] |
I have prepared a [sqlfiddle](http://sqlfiddle.com/#!3/844e0) workspace which you can see the question and solve it easily.
There is a table include ID, DAT, AMN, FLWC, FLWD, TYP.
I would like to sort table by DAT and ID (DAT is first keyword in sort)
then update FLWC and FLWD from previous record depend on TYP.
for example if 0:previous record and 1:current record then:
```
if typ1==d then (flwc1=flwc0 AND flwd1=flwd0+amn1)
if typ1==c then (flwc1=flwc0+amn AND flwd1=flwd0)
```
You can see that flwc and flwd will be set to next record and one of them will be sum to AMN depend on TYP value.
Table before changes:
```
-- id__dat__amn__flwc__flwd__typ
-- 1 10 100 0 0 d
-- 2 11 200 0 0 c
-- 3 12 300 0 0 d
-- 4 13 400 0 0 c
-- 5 14 500 0 0 d
-- 6 15 600 0 0 c
-- 7 16 700 0 0 d
```
Table after UPDATE:
```
-- id__dat__amn__flwc__flwd__typ
-- 1 10 100 0 100 d
-- 2 11 200 200 100 c
-- 3 12 300 200 400 d
-- 4 13 400 600 400 c
-- 5 14 500 600 900 d
-- 6 15 600 1200 900 c
-- 7 16 700 1200 1600 d
```
Please note that in real test the DAT fields might be equal in several records because DAT means DATE.
I have checked some answer from others but they don't have condition in their answers.
**Live test: [sqlfiddle](http://sqlfiddle.com/#!3/844e0)** | Complicated question but easy answer! (it shows that the start point is very important to thinking about a question)
```
declare @sumc decimal
declare @sumd decimal
set @sumc=0
set @sumd=0
update myTable set
@sumc+= case typ when 'c' then amn else 0 end, flwc=@sumc,
@sumd+= case typ when 'd' then amn else 0 end, flwd=@sumd
``` | You should add two more column with bit values i.e. C and D. Value of C is one if typ is c and 0 if typ is d and in reverse for d.
```
for over i
{
flwc(i)=flwc(i-1)+amn*C(i)
flwd(i)=flwd(i-1)+amn*D(i)
}
```
---------------------------------- Edit ---------------------------------
This is pseudo-code of what you have to do. In SQL doing it requires some consecutive queries to be done.
In C#
```
//Initiation
SqlConnection Con=new SqlConnection(Some_Connection_String);
SqlCommand Comm=new SqlCommand("",Con);
Con.Open();
Comm.CommandText="SELECT TOP (1) id FROM table_name ORDER BY id DESC";
int MaxId=(int)Comm.ExecuteScaler();
int flwc=0,flwd=0;
int amn=0;
string typ="";
//Itteration
for (int Id=1;Id<MaxId;Id++)
{
Comm.CommandText = "UPDATE table_name SET flwc="+(flwc+amn*(typ=="c"?1:0)).ToString()+",flwd="+(flwd+amn*(typ=="d"?1:0)).ToString()+" WHERE id="+Id.ToString();
Comm.ExecuteNonQuery();
//Update
Comm.CommandText = "SELECT * FROM table_name WHERE id="+Id.ToString();
reader=Comm.ExecuteReader();
reader.Read();
amn=reader.GetInt32(2);
flwc=reader.GetInt32(3);
flwd=reader.GetInt32(4);
typ=reader.GetString(5);
}
Con.Close();
```
If I have no syntax or logical errors (!) this should work fine. | SQL Update records to sum of previous records with condition | [
"",
"sql",
"sql-server",
"stored-procedures",
"sql-update",
""
] |
I have this SQL line
```
SELECT No_, sum(Quantity) AS Sold, [Shipment Date] AS SoldDate, [Item Category Code],
Description, [Description 2] FROM dbo.[3S Company A_S$Sales Invoice Line]
WHERE [Item Category Code] = '5104' GROUP BY No_
```
But i got this error for my script.
```
Column 'dbo.3S Company A_S$Sales Invoice Line.Shipment Date' is invalid in the select
list because it is not contained in either an aggregate function or the GROUP BY clause.
```
Can anyone help me with why? | TRY THIS
```
SELECT No_, sum(Quantity) AS Sold, [Shipment Date] AS SoldDate, [Item Category Code],
Description, [Description 2] FROM dbo.[3S Company A_S$Sales Invoice Line]
WHERE [Item Category Code] = '5104' GROUP BY No_,[Shipment Date],
[ItemCategoryCode], Description,[Description 2]
```
IN SQL IF YOU USE ANY COLUMN NAME IN SELECT CLAUSE EXCEPT AGGREGRATE FUNCTION THEN YOU NEED TO ADD ALL THE COLUMNS IN GROUP BY ALSO OTHER WISE IT WILL SHOW EXCEPTION
IF YOU WANT SUM ONLY BY NO\_ Column then you have to write a subquery with the aggregarte function and join it to you other columns as folows
```
SELECT No_ ,quant.sold, [Shipment Date] AS SoldDate, [Item Category Code],
Description, [Description 2] FROM dbo.[3S Company A_S$Sales Invoice Line] INV,
(SELECT No_, sum(Quantity) AS Sold from dbo.[3S Company A_S$Sales Invoice Line] where
WHERE [Item Category Code] = '5104' group by No_) quant
WHERE [Item Category Code] = '5104' and
inv.no_=quant.no_
``` | If you use `GROUP BY` in your query, only the columns used in your grouping clause and any aggregate functions like `SUM` are allowed in the select list. In your case, you specify `GROUP BY No_`, so that is the only column you can select without using an aggregate function.
If you want to get the remaining columns, you could select `No_` and the other aggregate columns in a subquery and then select other columns by matching the `No_` column with the corresponding column in subquery. | Error in SQL sum() | [
"",
"sql",
"sql-server",
""
] |
I have a large table containns 20,000 records. I want to find similar records(duplicate records on those BNO and BNO-CSCcode columns)
```
CSCcode Description BNO BNO-CSCcode EID
05078 blah1 5430 5430-05078 1098
05026 blah2 5431 5431-05026 1077
05026 blah3 5431 5431-05026 3011
04020 blah4 8580 8580-04020 3000
07620 blah5 7560 7560-07620 7890
07620 blah6 7560 7560-07620 8560
05020 blah1 5560 5560-04020 1056
01234 sampledesc 0009 0009-01234 1156
04567 sampledesc2 0056 0056-04567 1656
01234 sampledesc8 0009 0009-01234 0023
```
I want to retrieve like
```
CSCcode Description BNO BNO-CSCcode EID
05026 blah2 5431 5431-05026 1077
05026 blah3 5431 5431-05026 3011
07620 blah5 7560 7560-07620 7890
07620 blah6 7560 7560-07620 8560
01234 sampledesc 0009 0009-01234 1156
01234 sampledesc8 0009 0009-01234 0023
```
How do i specify that in sql query. | ```
select t1.*
from table_name t1
inner join (select BNO,BNO-CSCcode
from table_name
group BNO,BNO-CSCcode
having count(1)>1) as t2
on t1.BNO=t2.BNO and t1.BNO-CSCcode=t2.BNO-CSCcode
``` | You will have to use `EXISTS` command in your query.
This will give the desired resuilt:
```
SELECT *
FROM TableName t0
WHERE EXISTS (
SELECT 1
FROM TableName t1
WHERE t0.BNO = t1.BNO AND t0.BNOCSC = t1.BNOCSC
GROUP BY BNO, BNOCSC
HAVING count(*) > 1
)
```
`EXISTS` is used for comparison between one or more than one column. | How to find duplicates in two columns access sql | [
"",
"sql",
"ms-access",
""
] |
I have the following table test
```
iD Name ParentId GroupID DisplayingOrder
---------------------------------------------
1 1 1 Null
2 1 1 Null
3 1 1 Null
4 7 2 Null
5 7 2 Null
6 7 2 Null
7 9 3 Null
```
How can I modify it to get
```
iD Name ParentId GroupID DisplayingOrder
---------------------------------------------
1 1 1 1
2 1 1 2
3 1 1 3
4 7 2 1
5 7 2 2
6 7 2 3
7 9 3 1
```
Logic : increment DisplayingOrder for the same GroupID | You can do the both UPDATES in one query you dont need to break it down in two statements. see below :
```
; WITH CTE
AS
(
SELECT iDName, ParentId, GroupID,DisplayingOrder
,DENSE_RANK() OVER (ORDER BY ParentId ASC) RN1
,ROW_NUMBER() OVER (PARTITION BY ParentId ORDER BY ParentId) RN2
FROM TEST
)
UPDATE CTE
SET GroupID = RN1
,DisplayingOrder = RN2
```
## [`Sql Fiddle`](http://sqlfiddle.com/#!3/0403c/1)
Also if you can have a look at [`SQL SERVER RANKING FUNCTIONS`](http://technet.microsoft.com/en-us/library/ms189798.aspx), it will really help you :) | This isn't an exact duplicate of the earlier question. But a very similar approach can work:
```
WITH toupdate AS
(SELECT iDName, ParentId, GroupID,
row_number() over (partition by groupid order by idName) as newDisplayingOrder
FROM test t
)
UPDATE toupdate
SET DisplayingOrder = newDisplayingOrder;
```
You can do both in one step:
```
WITH toupdate AS
(SELECT t.*,
dense_rank() over (order by ParentId) as newGroupId,
row_number() over (partition by groupid order by idName) as newDisplayingOrder
FROM test t
)
UPDATE toupdate
SET GroupId = newGroupId,
DisplayingOrder = newDisplayingOrder;
``` | Modify a column in a table | [
"",
"sql",
""
] |
I have two tables as shown below.
First Table `tblCategory`

Second Table `tblWord`

`Required Output`

On output,
`TotalCount` is `count(*)` with `group by categoryid` from `tblWord`
`Played` is `count(*)` with `where isPlayed = 1 group by categoryid` from `tblword`
So for getting result from 2 table, I tried following query which is wrong.
```
select (select count(*) from tblwords group by categoryid) as count, (select count(*) from tblwords where isPlayed = 1 group by categoryid) as played, categoryID, categoryname from tblcategory
```
Any suggestion in query to get required output or any helpful links ? | To get exact output with total count
```
SELECT t.categoryID, t.name,
COUNT(*) as TotalCount, SUM(isplayed) as Played
FROM tblCategory t
INNER JOIN tblWord tw
ON t.categoryID = tw.categoryID
GROUP BY t.categoryID, t.name
```
To get count for isPlayed = 1 only
```
SELECT t.categoryID, t.name,
COUNT(*) as TotalCount, SUM(isplayed) as Played
FROM tblCategory t
INNER JOIN tblWord tw
ON t.categoryID = tw.categoryID
WHERE isPlayed=1
GROUP BY t.categoryID, t.name
``` | try this
```
SELECT tw.Category_ID, tc.NAME,
COUNT(*) AS TotalCount, SUM(tw.IsPlayed=1) AS Played ,SUM(tw.IsPlayed=0) AS NonPlayed
FROM Table_Category tc
INNER JOIN Table_Word tw
ON tc.Category_ID = tw.Category_ID
-- WHERE tw.IsPlayed=1
GROUP BY tc.Category_ID, tc.NAME
```
here `SUM(tw.IsPlayed=1) AS Played ,SUM(tw.IsPlayed=0) AS NonPlayed` is used ,so u will get the both Played and non played | SQL : Count(*) and groupby with different table | [
"",
"sql",
"sqlite",
""
] |
I have a following tables:
`sensors:`
```
id name key code
1 s1 abc 123
2 s2 def 456
3 s3 ghi 789
```
`measurements:`
```
id value sensor_id generated_at
1 1.0 1 2013-12-30 06:00:00
2 1.0 1 2013-12-30 06:01:00
3 1.0 1 2013-12-30 06:02:00
4 3.0 2 2013-12-30 07:00:00
5 3.0 2 2013-12-30 07:01:00
6 3.0 2 2013-12-30 07:05:00
7 5.0 3 2013-12-30 08:02:00
8 5.0 3 2013-12-30 08:03:00
9 5.0 3 2013-12-30 08:11:00
10 5.0 3 2013-12-30 08:15:00
```
What I want to do is to generate report with all sensors data and include first and last `generated_at` time for received measurements, so the result of MySQL request should look like:
```
id name key code first_value_generated_at last_value_generated_at
1 s1 abc 123 2013-12-30 06:00:00 2013-12-30 06:02:00
2 s2 def 456 2013-12-30 07:00:00 2013-12-30 07:05:00
3 s3 ghi 789 2013-12-30 08:02:00 2013-12-30 08:15:00
```
I would appreciate any help, thanks. | I don't think that `LEFT JOIN` is really necessary here (only in case when there more or less `sensors.id` than in `measurements.sensor_id`). **SQL** query is below :
```
SELECT
s.id,
s.name,
s.key,
s.code,
m.first_value_generated_at,
m.last_value_generated_at
FROM sensors s JOIN
(SELECT
sensor_id,
MIN(generated_at) as first_value_generated_at,
MAX(generated_at) as last_value_generated_at
FROM
measurements
GROUP BY
sensor_id
) m ON s.id = m.sensor_id
ORDER BY
s.id
``` | I hope this should work for you,
```
select *
,(select min(generated_at) from measurements as a where a.sensor_id =s.id) as first_value_generated_at
,(select max(generated_at) from measurements as b where b.sensor_id =s.id) as last_value_generated_at
from sensors as s
``` | MySQL LEFT JOIN dates with order | [
"",
"mysql",
"sql",
"date",
"join",
"left-join",
""
] |
could someone please have a quick look at the query i am writing below. A synopsis of what this query is suppose to be doing is to put the two characters "xx" in the field "Query04priorityselect" for all records where priority = "high". It seems that all is working other than the second to last line. The error message I get is "syntax error, missing operator" upon executing the query.
Thanks,
```
Private Sub Opzione61_GotFocus()
' identifies table to be updated
Dim Recordset
Set Recordset = CurrentDb.OpenRecordset("tblsearchengine01")
' puts a 1 value in the field Query04PrioritySelect for all records
Dim ClearPriority
ClearPriority = "UPDATE tblsearchengine01 SET Query04priorityselect=1"
' Run the command. / perform the update
CurrentDb.Execute ClearPriority
Dim HighPriority
HighPriority = "UPDATE tblsearchengine01 SET Query04priorityselect = ""xx"" & WHERE Priority<>high"
CurrentDb.Execute HighPriority
End Sub
``` | I think you need to quote the word *high* in the `WHERE` clause. Single quotes are fine in Access SQL statements.
```
HighPriority = "UPDATE tblsearchengine01" & vbCrLf & _
"SET Query04priorityselect = 'xx' WHERE Priority <> 'high'"
Debug.Print HighPriority
CurrentDb.Execute HighPriority
```
If the query still throws an error, go to the Immediate window and copy the statement text which was output from `Debug.Print`. You can then create a new query in the Access query designer, switch it to SQL View, paste in the copied text and test that statement. Hopefully you can figure out how to fix the error. If not, copy the statement text and include it in your question. | ```
Dim HighPriority
HighPriority = "UPDATE tblsearchengine01 SET Query04priorityselect ='xx' WHERE Priority<>high "
CurrentDb.Execute HighPriority
``` | Update query with SQL | [
"",
"sql",
"ms-access",
"vba",
"ms-access-2013",
""
] |
Table:
```
+-------------+
| izvajalecID |
+-------------+
| 20 |
| 21 |
| 21 |
| 20 |
| 21 |
+-------------+
```
I would like to count all the unique ID's and print their values.
For example:
Unique ID's: **2**
Values: **20, 21**
I tried with the following query. Count works fine, but it returns only one(first) value. What am i doing wrong?
```
SELECT COUNT(distinct izvajalecID), s.izvajalecID FROM (SELECT izvajalecID FROM servis) s;
``` | ```
SELECT
izvajalecID
FROM
servis
GROUP BY
izvajalecID
UNION
SELECT
COUNT(DISTINCT izvajalecID)
FROM
servis
```
[**Fiddle**](http://www.sqlfiddle.com/#!2/5f1c3/1)
The last value in the set is for COUNT of unique values. You can also change them places and it will be the first value, just as you wish. | Try this:
```
SELECT izvajalecID, COUNT(DISTINCT izvajalecID) as COUNT
FROM servis
GROUP BY izvajalecID
```
Result:
```
IZVAJALECID COUNT
20 1
21 1
```
See result in [**SQL Fiddle**](http://www.sqlfiddle.com/#!2/e5fa9/2). | MySQL: Print counted values | [
"",
"mysql",
"sql",
""
] |
My previous question is very confusing. I am so sorry for my carelessness. Here, I posted my question again with more information.
My table A and table B has same column names(name,id,age,date,class,...) but different number of rows. Table B is a duplicate table of table A and has fewer rows. What I want to know is how I can retrieve the records if they have the same primary key(id) and any of the other column fields (name, age, date, class,...) are different. However, there is one condition. Although the records have same primary key, if only date is changed, records should not be retrieved.Only when the two tables have same primary key, date is different and any of the column fields is changed, the records should be retrieved.
Since there are around 200k records, and around 100 columns, I would like to use advanced SQL, since my SQL will be too long if I use `Select.. from... where`, but I don't know which SQL to use.
`TableA`:
```
name age id date
------ --- -- ----------
David 11 1 11/01/2014
Claire 16 2 13/03/2014
Max 15 3 20/02/2014
John 14 4 19/09/2014
James 12 5 16/06/2014
```
`TableB`:
```
name age id date
----- --- -- ----------
Max 15 3 15/05/2014
Will 14 4 12/04/2014
Bill 12 7 11/04/2014
Paul 11 8 24/12/2013
Kevin 13 9 03/04/2014
```
Output expected:
```
TableA TableB
name age id date name age id date
---- --- -- ---------- ---- --- -- ----------
John 14 4 19/09/2014 Will 14 4 12/04/2014
```
Thanks! | Since you want to check for all columns writing a where clause for it might be tedious so you can use `information_schema.columns` to get the column names for that table and then using a dynamic query you can check for column differences.
The following might be the solution to your problem.
```
--Simulate your table structure
CREATE TABLE TableA
(
NAME VARCHAR(100),
AGE INT,
ID INT,
DATE_COL DATETIME
)
CREATE TABLE TableB
(
NAME VARCHAR(100),
AGE INT,
ID INT,
DATE_COL DATETIME
)
--Data for testing
INSERT INTO TABLEA(NAME, AGE, ID, DATE_COL) VALUES('David',11,1,'01/11/2014')
INSERT INTO TABLEA(NAME, AGE, ID, DATE_COL) VALUES('Claire',16,2,'03/13/2014')
INSERT INTO TABLEA(NAME, AGE, ID, DATE_COL) VALUES('Max',15,3,'02/20/2014')
INSERT INTO TABLEA(NAME, AGE, ID, DATE_COL) VALUES('John',14,4,'09/19/2014')
INSERT INTO TABLEA(NAME, AGE, ID, DATE_COL) VALUES('James',12,5,'06/16/2014')
INSERT INTO TABLEB(NAME, AGE, ID, DATE_COL) VALUES('Max',15,3,'05/15/2014')
INSERT INTO TABLEB(NAME, AGE, ID, DATE_COL) VALUES('Will',14,4,'04/12/2014')
INSERT INTO TABLEB(NAME, AGE, ID, DATE_COL) VALUES('Bill',12,7,'04/11/2014')
INSERT INTO TABLEB(NAME, AGE, ID, DATE_COL) VALUES('Paul',11,8,'12/24/2013')
INSERT INTO TABLEB(NAME, AGE, ID, DATE_COL) VALUES('Kevin',13,9,'04/03/2014')
--Solution Starts from here
CREATE TABLE #TableCols
(
ID INT IDENTITY(1,1),
COLUMN_NAME VARCHAR(1000)
)
--since both tables have same columns you can take columns of any 1 table
INSERT INTO #TableCols
(COLUMN_NAME)
SELECT COLUMN_NAME
FROM information_schema.columns
WHERE table_name = 'TableA';
DECLARE @STARTCOUNT INT, @MAXCOUNT INT, @COL_NAME VARCHAR(1000), @QUERY VARCHAR(8000), @SUBQUERY VARCHAR(8000)
SELECT @STARTCOUNT = 1, @MAXCOUNT = MAX(ID) FROM #TableCols;
SELECT @QUERY = '', @SUBQUERY = ''
WHILE(@STARTCOUNT <= @MAXCOUNT)
BEGIN
SELECT @COL_NAME = COLUMN_NAME FROM #TableCols WHERE ID = @STARTCOUNT;
IF(@COL_NAME != 'DATE_COL' AND @COL_NAME != 'ID')
BEGIN
SET @SUBQUERY = @SUBQUERY + ' A.' + @COL_NAME + ' != B.' + @COL_NAME + ' OR ';
END
SET @STARTCOUNT = @STARTCOUNT + 1
END
SET @SUBQUERY = LEFT(@SUBQUERY, LEN(@SUBQUERY) - 3);
SET @QUERY = 'SELECT A.*, B.* FROM TableA A INNER JOIN TableB B ON A.ID = B.ID WHERE A.DATE_COL != B.DATE_COL AND (' + @SUBQUERY + ')';
EXEC (@QUERY);
```
Hope this helps. | You can use strcmp() function to compare the string.
<http://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html#function_strcmp>
for example you want to compare name and age from both table then your query should be like below:
```
select * from (select A.*,B.*,strcmp(concat(A.name,',',A.age),concat(B.name,',',B.age)) as diff from TableA A inner join TableB B on A.id = B.id)tablealias where tablealias.diff!=0
```
include the fields in strcmp function that you bother if they change | How to get the records back from two tables with same primary key if any of the other column fields are changed | [
"",
"sql",
"sql-server",
"database",
""
] |
Please see the code below:
```
SELECT
mp_asin.CATEGORY_CODE AS Category_id
,mp_asin.SUBCATEGORY_CODE AS SUBCATEGORY
,mp_asin.PARENT_ASIN
,mp_asin.PARENT_ASIN_NAME
,mp_asin.COLOR_NAME AS Color_Name
,mp_asin.PRODUCT_SITE_LAUNCH_DAY AS PSLD
,mp_asin.PARENT_ASIN_NAME || ', ' || mp_asin.COLOR_NAME as TEEN
,mp_asin.BRAND_CODE AS Brand_Code
,mp_asin.REPLENISHMENT_CODE as REPLEN_CODE
,mp_asin.REPLENISHMENT_CATEGORY_ID AS Replen_TIER
,mp_asin.ASIN as ASIN
,MIN(mp.REPLENISHMENT_CODE) OVER (PARTITION BY (mp_asin.PARENT_ASIN_NAME || ', ' || mp_asin.COLOR_NAME)) as MIN_TEEN_RC
,MAX(mp.REPLENISHMENT_CODE) OVER (PARTITION BY (mp_asin.PARENT_ASIN_NAME || ', ' || mp_asin.COLOR_NAME)) as MAX_TEEN_RC
FROM
d_mp_asins mp_asin
WHERE
MIN_TEEN_RC <> MAX_TEEN_RC
AND mp_asin.CATEGORY_CODE =('30905500')
AND mp_asin.SUBCATEGORY_CODE =('30905560')
AND mp_asin.REGION_ID = 1
AND mp_asin.MARKETPLACE_ID = 1
AND mp_asin.GL_PRODUCT_GROUP = 309
```
My error seems to be in the `Where` clause. Is there another way to write
```
Min_Teen_RC <> MAX_TEEN_RC
```
I tried the following and got the same error:
```
MIN(mp.REPLENISHMENT_CODE) OVER (PARTITION BY (mp_asin.PARENT_ASIN_NAME || ', ' || mp_asin.COLOR_NAME)) <> MAX(mp.REPLENISHMENT_CODE) OVER (PARTITION BY (mp_asin.PARENT_ASIN_NAME || ', ' || mp_asin.COLOR_NAME))
```
Here is the error I am getting:
> ORA-00904: "MAX\_TEEN\_RC": invalid identifier
Thanks for your help!
Here is the entire code for V2:
```
SELECT
mp_asin.CATEGORY_CODE AS Category_id
,mp_asin.SUBCATEGORY_CODE AS SUBCATEGORY
,mp_asin.PARENT_ASIN
,mp_asin.PARENT_ASIN_NAME
,mp_asin.COLOR_NAME AS Color_Name
,mp_asin.PRODUCT_SITE_LAUNCH_DAY AS PSLD
,mp_asin.PARENT_ASIN_NAME || ', ' || mp_asin.COLOR_NAME as TEEN
,mp_asin.BRAND_CODE AS Brand_Code
,mp_asin.REPLENISHMENT_CODE as REPLEN_CODE
,mp_asin.REPLENISHMENT_CATEGORY_ID AS Replen_TIER
,mp_asin.ASIN as ASIN
,MIN(mp.REPLENISHMENT_CODE) OVER (PARTITION BY (mp_asin.PARENT_ASIN_NAME || ', ' || mp_asin.COLOR_NAME)) as MIN_TEEN_RC
,MAX(mp.REPLENISHMENT_CODE) OVER (PARTITION BY (mp_asin.PARENT_ASIN_NAME || ', ' || mp_asin.COLOR_NAME)) as MAX_TEEN_RC
FROM
d_mp_asins mp_asin
WHERE
MIN(mp.REPLENISHMENT_CODE) OVER (PARTITION BY (mp_asin.PARENT_ASIN_NAME || ', ' || mp_asin.COLOR_NAME)) <> MAX(mp.REPLENISHMENT_CODE) OVER (PARTITION BY (mp_asin.PARENT_ASIN_NAME || ', ' || mp_asin.COLOR_NAME))
AND mp_asin.CATEGORY_CODE =('30905500')
AND mp_asin.SUBCATEGORY_CODE =('30905560')
AND mp_asin.REGION_ID = 1
AND mp_asin.MARKETPLACE_ID = 1
AND mp_asin.GL_PRODUCT_GROUP = 309
Group by
mp_asin.CATEGORY_CODE
,mp_asin.SUBCATEGORY_CODE
,mp_asin.PARENT_ASIN
,mp_asin.PARENT_ASIN_NAME
,mp_asin.COLOR_NAME
,mp_asin.PRODUCT_SITE_LAUNCH_DAY
,mp_asin.PARENT_ASIN_NAME || ', ' || mp_asin.COLOR_NAME
,mp_asin.BRAND_CODE
,mp_asin.REPLENISHMENT_CODE
,mp_asin.REPLENISHMENT_CATEGORY_ID
,mp_asin.ASIN
``` | Try this -
```
SELECT * FROM
(
SELECT
mp_asin.CATEGORY_CODE AS Category_id
,mp_asin.SUBCATEGORY_CODE AS SUBCATEGORY
,mp_asin.PARENT_ASIN
,mp_asin.PARENT_ASIN_NAME
,mp_asin.COLOR_NAME AS Color_Name
,mp_asin.PRODUCT_SITE_LAUNCH_DAY AS PSLD
,mp_asin.PARENT_ASIN_NAME || ', ' || mp_asin.COLOR_NAME as TEEN
,mp_asin.BRAND_CODE AS Brand_Code
,mp_asin.REPLENISHMENT_CODE as REPLEN_CODE
,mp_asin.REPLENISHMENT_CATEGORY_ID AS Replen_TIER
,mp_asin.ASIN as ASIN
,MIN(mp.REPLENISHMENT_CODE) OVER (PARTITION BY (mp_asin.PARENT_ASIN_NAME || ', ' || mp_asin.COLOR_NAME)) as MIN_TEEN_RC
,MAX(mp.REPLENISHMENT_CODE) OVER (PARTITION BY (mp_asin.PARENT_ASIN_NAME || ', ' || mp_asin.COLOR_NAME)) as MAX_TEEN_RC
FROM
d_mp_asins mp_asin
WHERE 1=1
AND mp_asin.CATEGORY_CODE =('30905500')
AND mp_asin.SUBCATEGORY_CODE =('30905560')
AND mp_asin.REGION_ID = 1
AND mp_asin.MARKETPLACE_ID = 1
AND mp_asin.GL_PRODUCT_GROUP = 309
)
where MIN_TEEN_RC <> MAX_TEEN_RC;
``` | > **ORA-00904** can simply be avoided by using the valid column name in
> create or alter statement. Also for DML statements ORA-00904 can be
> avoided by making a valid reference to the column name or the alias.
Try this
```
SELECT * FROM
(
SELECT
mp_asin.CATEGORY_CODE AS Category_id
,mp_asin.SUBCATEGORY_CODE AS SUBCATEGORY
,mp_asin.PARENT_ASIN
,mp_asin.PARENT_ASIN_NAME
,mp_asin.COLOR_NAME AS Color_Name
,mp_asin.PRODUCT_SITE_LAUNCH_DAY AS PSLD
,mp_asin.PARENT_ASIN_NAME || ', ' || mp_asin.COLOR_NAME as TEEN
,mp_asin.BRAND_CODE AS Brand_Code
,mp_asin.REPLENISHMENT_CODE as REPLEN_CODE
,mp_asin.REPLENISHMENT_CATEGORY_ID AS Replen_TIER
,mp_asin.ASIN as ASIN
,MIN(mp.REPLENISHMENT_CODE) OVER (PARTITION BY (mp_asin.PARENT_ASIN_NAME || ', ' || mp_asin.COLOR_NAME)) as MIN_TEEN_RC
,MAX(mp.REPLENISHMENT_CODE) OVER (PARTITION BY (mp_asin.PARENT_ASIN_NAME || ', ' || mp_asin.COLOR_NAME)) as MAX_TEEN_RC
FROM
d_mp_asins mp_asin
) T
WHERE
T.MIN_TEEN_RC <> T.MAX_TEEN_RC
AND T.CATEGORY_CODE =('30905500')
AND T.SUBCATEGORY_CODE =('30905560')
AND T.REGION_ID = 1
AND T.MARKETPLACE_ID = 1
AND T.GL_PRODUCT_GROUP = 309
``` | Partition by and invalid identifier | [
"",
"sql",
"oracle",
""
] |
Here is the schema
Employee (name,sex,salary,deptName)
and name is the primary key
```
SELECT deptname
FROM employee
WHERE sex=m
GROUP BY deptName HAVING avg(salary) >
(SELECT avg(salary)
FROM employee)
```
I want to understand the part `having avg(salary)` what does that part actually do?
since we dont include the salary select clause,
```
SELECT deptname
FROM employee
WHERE sex=m
GROUP BY deptName
```
This part will give me group of deptName, just one column nothing else, I am wondering how having (avg(salary)) is working, it is taking avg of all employees from the table or what?
Anyone who can tell me
Thanks | `WHERE` filters records *before* they are grouped; whereas `HAVING` filters the results *after* they have been grouped. Expressions, using functions or operators, can be used in either clause (although aggregate functions like `AVG()` cannot be used in the `WHERE` clause as the records would not have been grouped when that clause is evaluated).
Thus your query filters a list of departments for those where the average salary of that department's male workers is greater than the overall (company) average salary. | ```
SELECT AVG(salary)
FROM employee
```
By above query first you will get avg salary of all employees.
Now you are getting only department whose avg salary is greater than avg salary of all employees. | having clause works with where in mysql | [
"",
"mysql",
"sql",
"group-by",
"where-clause",
"having",
""
] |
```
SELECT contents.*,
(SELECT COUNT(*)
FROM comments
WHERE comments.scrap_id = contents.org_scrap_id) AS comment_count
FROM contents
ORDER BY comment_count
```
this is my intention. but it makes very long waits.
how can i increase the performance of this query? | You can increase the performance by creating an index on `comments(scrap_id)`:
```
create index comments_scrap_id on comments(scrap_id);
```
You could also try phrasing this as a `join` and `group by`:
```
SELECT co.*, count(com.scrap_id) as comment_count
FROM contents co left outer join
comments com
on co.org_scrap_id = com.scrap_id
GROUP BY co.id
---------^ or whatever the appropriate `id` is for this table
ORDER BY comment_count;
```
But the index is likely to give better performance. | You can rewrite your query using join,but for performance an explain plan is needed,you are using a correlated subquery which will run for each row in contents table and can reduce the performance of query, for below query you need an index for `scrap_id` from comments table and `org_scrap_id` from contents table if its not a primary key
```
SELECT c.*, COUNT(cm.scrap_id) comment_count
LEFT JOIN comments cm
ON cm.scrap_id = c.org_scrap_id
FROM contents c
GROUP BY c.org_scrap_id
ORDER BY comment_count
``` | how can i increase the performance of SQL?(sub query is used) | [
"",
"mysql",
"sql",
"database-performance",
""
] |
I am trying to find the difference between the current row and the previous row. However, I am getting the following error message:
> The multi-part identifier "tableName" could not be bound.
Not sure how to fix the error.
Thanks!
Output should look like the following:
```
columnOfNumbers Difference
1 NULL
2 1
3 1
10 7
12 2
.... ....
```
Code:
```
USE DATABASE;
WITH CTE AS
(SELECT
ROW_NUMBER() OVER (PARTITION BY tableName ORDER BY columnOfNumbers) ROW,
columnOfNumbers
FROM tableName)
SELECT
a.columnOfNumbers
FROM
CTE a
LEFT JOIN CTE b
ON a.columnOfNumbers = b.columnOfNumbers AND a.ROW = b.ROW + 1
``` | See [sqlFiddle](http://sqlfiddle.com/#!3/ad6e5/1)
```
;WITH tblDifference AS
(
SELECT ROW_NUMBER() OVER(ORDER BY id) AS RowNumber, columnOfNumbers
FROM tableName
)
SELECT cur.columnOfNumbers, cur.columnOfNumbers - previous.columnOfNumbers
FROM tblDifference cur
LEFT OUTER JOIN tblDifference previous
ON cur.RowNumber = previous.RowNumber + 1
``` | If you in SQL Server 2012+ You can use LAG.
```
SELECT columnOfNumbers
,columnOfNumbers - LAG(columnOfNumbers, 1) OVER (ORDER BY columnOfNumbers)
FROM tableName
```
Note: The optional third parameter of LAG is:
> default
>
> The value to return when scalar\_expression at offset is NULL.
> If a default value is not specified, NULL is returned. default can be
> a column, subquery, or other expression, but it cannot be an analytic
> function. default must be type-compatible with scalar\_expression. | SQL Find difference between previous and current row | [
"",
"sql",
"sql-server",
""
] |
I need to count the number of rows in a table with a single SQL query.
That query should not contain any aggregate function like `COUNT`. | Easy way:
```
DECLARE @i INT = 0
SELECT @i = @i + 1
FROM <WHAT EVER>
SELECT @i AS RC
```
Fast, effective and no need for all sorts of sub queries as it requires only one run through the data :) | I'm a little surprised nobody has mentioned this yet:
```
EXEC sp_spaceused @objname = N'MyTable', @updateusage = 'TRUE'
```
This will, among other things return the current count of records in the table.
This would also work in most cases:
```
SELECT rows
FROM sys.partitions
WHERE index_id IN (1,0)
AND object_id = OBJECT_ID(N'MyTable')
``` | Count number of rows without using any aggregate functions | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
""
] |
I want to make an addition of the sum of two queries (please see my queries below, these examples works). My problem is when one of the queries return a null result like
```
select (select sum(60+3+25+2))+(select sum(0)) as montant
```
the result of the addition is automatically NULL.
But when the 2 queries have results more than null like:
```
select (select sum(60+3+25+2))+(select sum(300+50)) as montant
```
the addition works and i get the right result:
here is the first query that gives me 90 as a result
```
select sum(lf.quantite) from fraisforfait f
inner join lignefraisforfait lf on lf.idFraisForfait = f.id
inner join fichefrais ff on ff.idVisiteur = lf.idVisiteur and ff.mois = lf.mois
where lf.idVisiteur = "a131" and lf.mois = "201312"
```
here is the second one that gives me 0 as a result
```
select sum(lfh.montant)
from lignefraishorsforfait lfh
inner join fichefrais ff on ff.idVisiteur = lfh.idVisiteur and ff.mois = lfh.mois
where ff.idVisiteur = "a131" and ff.mois = "201312"
```
here is the addition of the 2 queries that gives me a NULL result, but i expect 90:
```
select (select sum(lf.quantite) from fraisforfait f
inner join lignefraisforfait lf on lf.idFraisForfait = f.id
inner join fichefrais ff on ff.idVisiteur = lf.idVisiteur and ff.mois = lf.mois
where lf.idVisiteur = "a131" and lf.mois = "201401") + (select sum(lfh.montant)
from lignefraishorsforfait lfh
inner join fichefrais ff on ff.idVisiteur = lfh.idVisiteur and ff.mois = lfh.mois
where ff.idVisiteur = "a131" and ff.mois = "201401") as montantValide;
```
Does anyone has a solution to this problem? thanks for your time. | You need to add something that will turn your `NULL` in to a `0`.
```
select COALESCE(sum(lfh.montant), 0)
``` | You want something like this.
t-sql
```
select (select 1 value) + isnull((select null value),0);
```
mysql
```
select (select 1 value) + ifnull((select null value),0);
``` | sql addition of 2 queries return NULL | [
"",
"sql",
""
] |
i am creating a dynamic query in stored procedure. my stored procedure is as follows:
```
CREATE PROCEDURE `test1`(IN tab_name VARCHAR(40),IN w_team VARCHAR(40))
BEGIN
SET @t1 =CONCAT("SELECT * FROM ",tab_name," where team=",w_team);
PREPARE stmt3 FROM @t1;
EXECUTE stmt3;
DEALLOCATE PREPARE stmt3;
END
```
when i try to run it with the following call:
```
call test1 ('Test','SPA');
```
i get the following error message:
> Error Code: 1054. Unknown column 'SPA' in 'where clause'
i tested without where condition and it works fine, but with the where condition its not working, i tried using @ with the variable name but it still does not work.
Thanks for your help. | You missed to enclose the parameter `w_team` in `WHERE` clause.
Try like this:
```
SET @t1 =CONCAT("SELECT * FROM ",tab_name," where team='",w_team,"'");
```
**Explanation**:
Query from your code would be like:
```
SELECT * FROM Test where team=SPA
```
It will try find a column `SPA` which is not available, hence the error.
And we changed it to:
```
SELECT * FROM Test where team='SPA'
``` | > Error Code: 1054. Unknown column 'SPA' in 'where clause'
This happens when you do not enclose input string within quotes, and SQL engine tries to identify it as a column in the table being queried. But it fails as it can't find it.
But what happens when it finds such column?
It fetches results when it finds some matches on the column values.
Obviously this is not what one was expecting.
How to overcome this? Use Prepared Statements with dynamic input values.
You can use placeholders like `?` in stored procedures too on dynamic input values to use with `Prepared Statements`. The engine will handle escape characters and other string values when assigned to or compared within SQL expressions.
You just need to re-assign procedure inputs to one or more session variables, as required.
**Example on your procedure**:
```
CREATE PROCEDURE `test1`( IN tab_name VARCHAR(40), IN w_team VARCHAR(40) )
BEGIN
SET @t1 = CONCAT( 'SELECT * FROM ', tab_name, ' where team = ?' ); -- <-- placeholder
SET @w_team := w_team;
PREPARE stmt3 FROM @t1;
EXECUTE stmt3 USING @w_team; -- <-- input for placeholder
DEALLOCATE PREPARE stmt3;
END;
``` | mysql dynamic query in stored procedure | [
"",
"mysql",
"sql",
"stored-procedures",
""
] |
I am trying to convert a varchar field to a number, however, there is a set of common characters inside that field that need to be removed in order for me to successfully convert it to numeric.
the name of the field is UKSellPrice1
I need to remove the following strings from UKSellPrice1 BEFORE converting it to numeric:
```
'.00'
'£'
'n/a'
'$'
'#N/A'
```
How can I get this done?
at the moment I have the following:

```
;WITH R0 AS (
SELECT StyleCode
,ColourCode
,UKSellPrice1= CASE WHEN CHARINDEX('.00',UKSellPrice1,1) > 0
THEN REPLACE (UKSellPrice1,'.00','')
ELSE UKSellPrice1 END
,UKSellPrice2
FROM dbo.RangePlan
)
SELECT *
FROM R0
``` | I can think of two approaches.
The first is to use a bunch of nested `replace()` statements:
```
select replace(replace(replace(col, '$', ''), '£', ''), 'n/a', '')
```
and so on.
The second is to find the first digit and try converting from there. This requires complicated logic with `patindex()`. Here is an example:
```
select cast(left(substring(col, patindex('%[0-9]%', col), 1000),
patindex('%[^0-9]%', substring(col, patindex('%[0-9]%', col), 1000)) - 1
) as int)
``` | You could do this. Create a function to strip a way the unwanted chars like this:
```
CREATE FUNCTION [dbo].[fnRemovePatternFromString](@BUFFER VARCHAR(MAX), @PATTERN VARCHAR(128)) RETURNS VARCHAR(MAX) AS
BEGIN
DECLARE @POS INT = PATINDEX(@PATTERN, @BUFFER)
WHILE @POS > 0 BEGIN
SET @BUFFER = STUFF(@BUFFER, @POS, 1, '')
SET @POS = PATINDEX(@PATTERN, @BUFFER)
END
RETURN @BUFFER
END
```
Then call the scalared function on the column with a pattern like this:
```
;WITH R0 AS (
SELECT StyleCode
,ColourCode
,UKSellPrice1= CAST(dbo.fnRemovePatternFromString(UKSellPrice1,'%[£$#N/A.00]%') AS INT)
,UKSellPrice2
FROM dbo.RangePlan
)
SELECT *
FROM R0
```
Reference:
* [T-SQL strip all non-alpha and non-numeric characters](https://stackoverflow.com/questions/9636045/t-sql-strip-all-non-alpha-and-non-numeric-characters) | replace multiple values at the same time - in order to convert a string to a number | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have this table:
```
+----+---------+----------+-------+
| id | user_id | other_id | score |
+----+---------+----------+-------+
| 1 | 1 | 1 | 80 |
| 2 | 1 | 2 | 40 |
| 3 | 1 | 3 | 60 |
| 4 | 2 | 2 | 70 |
| 5 | 2 | 4 | 50 |
| 6 | 2 | 3 | 40 |
| 7 | 2 | 5 | 90 |
+----+---------+----------+-------+
```
I want to sort each `user_id` by `score` and only return maximum `n` (e.g., 2) rows for each `user_id`. So I want to get the result as:
```
+---+---+---+----+
| 1 | 1 | 1 | 80 |
| 3 | 1 | 3 | 60 |
| 7 | 2 | 5 | 90 |
| 4 | 2 | 2 | 70 |
+---+---+---+----+
``` | This can be easily done by using a subselect,comparing the count with same table
```
SELECT *
FROM Table1 t
WHERE
(
SELECT COUNT(*)
FROM Table1 t1
WHERE t1.user_id = t.user_id AND
t1.score >= t.score
) <= 2
ORDER BY t.user_id ASC,t.score DESC
```
[**Fiddle Demo**](http://www.sqlfiddle.com/#!2/98670e/4) | Try this:
```
SELECT
id, user_id, other_id, score
FROM
yourtable
WHERE
score = (SELECT MAX(score) FROM yourtable a
WHERE a.user_id = yourtable.user_id
AND a.other_id= yourtable.other_id);
``` | Is there a way to select a certain number of row for a certain column? | [
"",
"mysql",
"sql",
""
] |
I'm trying to insert data from excel sheet to sql database. The query is stored in a text file as follows:
```
insert into [demo].[dbo].[relative]
select *
from openrowset('Microsoft.Jet.OLEDB.4.0','Excel 8.0;Database=D:\relative.xls','select * from [sheet1$]');
```
When I am executing the following command:
```
sqlcmd -S ADMIN-PC/SEXPRESS -i d:\demo.txt.
```
it is showing this error:
> Msg 7357, Level 16, State 2, Server ADMIN-PC\SEXPRESS, Line 1
Can anyone please help in rectifying my problem. | Try using the sql server import vizard to create a new table from the xls file and then insert that data to the existing table from there. The problem you are having is maybe due to the non-compatibility between 64bit sql instance and 32 bit excel.
Or try using `bcp`
```
bcp demo.dbo.relative in "D:\relative.xls" -c -T
``` | You can create a shell script which will automatically read the insert commands from the .csv file and then write it to the database. If you want I can help you up with it. What you just need to do is to write all the insert statements in the .csv file.
```
#!/bin/ksh
sqlplus -silent /nolog << EOF > /dev/null
username/pwd@"Connection String"
set linesize 0;
set pagesize 0;
set echo off;
while read line; do
A=`echo "$line" | awk -F" " {print 1}`
and so on depends on the number of words in the insert statements.
$A $B
done < your_insert_statements.csv
```
It will read the .csv file and automatically insert the records in the database. | sql insert query through text file | [
"",
"sql",
"sql-server",
""
] |
I am trying to query a list of meetings from the most recent semester, where semester is determined by two fields (year, semester). Here's a basic outline of the schema:
```
Otherfields Year Semester
meeting1 2014 1
meeting2 2014 1
meeting3 2013 2
... etc ...
```
As the max should be considered for the Year first, and *then* the Semester, my results should look like this:
```
Otherfields Year Semester
meeting1 2014 1
meeting2 2014 1
```
Unfortunately simply using the MAX() function on each column separately will try to find Year=2014, Semester=2, which is incorrect. I tried a couple approaches using nested subqueries and inner joins but couldn't quite get something to work. What is the most straightforward approach to solving this? | Using a window function:
```
SELECT Year, Semester, RANK() OVER(ORDER BY Year DESC, Semester DESC) R
FROM your_table;
```
`R` will be a column containing the "rank" of the couple (Year, Semester). You can then use this column as a filter, for instance :
```
WITH TT AS (
SELECT Year, Semester, RANK() OVER(ORDER BY Year DESC, Semester DESC) R
FROM your_table
)
SELECT ...
FROM TT
WHERE R = 1;
```
If you don't want gaps between ranks, you can use `dense_rank` instead of `rank`.
This answer assumes you use a RDBMS who is advanced enough to offer window functions (i.e. not MySQL) | I wouldn't be surprised if there's a more effecient way to do this (and avoid the duplicate subquery), but this will get you the answer you want:
```
SELECT * FROM table WHERE Year =
(SELECT MAX(Year) FROM table)
AND Semester =
(SELECT MAX(Semester) FROM table WHERE Year =
(SELECT MAX(Year) FROM table))
``` | Find max over multiple columns | [
"",
"sql",
"oracle11g",
""
] |
I have three tables:
```
pindex_photos: pindex_names: pindex_link:
| id | filename | | id | name | | photo_id | name_id |
|-----|-----------| |----|-------| |----------|---------|
| 1 | DSC1.jpg | | 1 | Leo | | 1 | 3 |
| 2 | DSC2.jpg | | 2 | Liz | | 1 | 2 |
| 3 | DSC5.jpg | | 3 | Tom | | 3 | 1 |
| .. | .. | | .. | .. | | 2 | 1 |
| .. | .. |
```
In pindex\_link the two first tables relate together with their id.
Now I would like to make a Report File From this Tables like:
```
Report on Images (list only Images that have > 0 connections to names)
DSC1.jpg (2): Liz, Tom
DSC2.jpg (1): Leo
..
Report on Names (list only Names that have > 0 connections to images)
Leo (2): DSC2.jpg, DSC5.jpg
Liz (1): DSC1.jpg
..
```
Can me anyone give me help or a clue how to achieve this? | ```
select p.filename, group_concat(n.name)
from pindex_photos p
left join pindex_link l on l.photo_id = p.id
left join pindex_names n on l.name_id = n.id
group by p.filename
```
and
```
select n.name, group_concat(p.filename)
from pindex_photos p
left join pindex_link l on l.photo_id = p.id
left join pindex_names n on l.name_id = n.id
group by n.name
``` | **Report on Images:**
```
SELECT p.id,COUNT(pn.name) as Count,group_concat(pn.name)
FROM pindex_link pl LEFT JOIN
pindex_photos p on p.id=pl.photo_id INNER JOIN
pindex_names pn on pn.id=pl.name_id
GROUP BY p.id
```
Result:
```
ID COUNT GROUP_CONCAT(PN.NAME)
1 2 Liz,Tom
2 1 Leo
3 1 Leo
```
See result in [**SQL Fiddle**](http://www.sqlfiddle.com/#!2/6929e/12).
**Report on Names:**
```
SELECT pn.name,COUNT(p.filename) as Count,group_concat(p.filename)
FROM pindex_link pl LEFT JOIN
pindex_photos p on p.id=pl.photo_id INNER JOIN
pindex_names pn on pn.id=pl.name_id
GROUP BY pn.name
```
Result:
```
NAME COUNT GROUP_CONCAT(P.FILENAME)
Leo 2 DSC5.jpg,DSC2.jpg
Liz 1 DSC1.jpg
Tom 1 DSC1.jpg
```
See result in [**SQL Fiddle**](http://www.sqlfiddle.com/#!2/6929e/13). | How to create a report from joined sql tables? | [
"",
"mysql",
"sql",
"join",
"report",
""
] |
I am learning SQL Server and am confused as to whether I should put `City`, `State` and `Country` in one table or should I create 3 different tables with foreign keys?

Please suggest which one is best for performance and future modifications etc. | The second one is better, as rule of thumb, always say if I need to rename a 'country' name how many records should be updated, if your answer is 1 then your design is good. (In first design the number of records that should be updated is as much as number of cities in that contry) | The second, normalized one, is better, of course.
But you don't need CountryId in City table, if city is dependant on state and only indirectly on country. | SQL Server database design, which one is better design | [
"",
"sql",
"sql-server",
""
] |
Every 15 minutes we read 250 XML files. Each XML file is an *element*. Each element (xml file) is composed of 5 sub-elements and each sub-element has 400 counters.
All those counters will be used for formulas and aggregations. What's the most efficient way of storing this data into tables, in this case t-sql tables?
Data can look like this. This is one XML file, there are 249 more like this:
```
[Element 1]
- [Element 1-1]
- [Counter 1]: 54
- [Counter 2]: 12
- [Counter 3]: 6
- ...
- [Counter 400]: 9
- [Element 1-2]
- [Counter 1]: 43
- [Counter 2]: 65
- [Counter 3]: 98
- ...
- [Counter 400]: 12
- [Element 1-3]
- [Counter 1]: 43
- [Counter 2]: 23
- [Counter 3]: 64
- ...
- [Counter 400]: 1
- [Element 1-4]
- [Counter 1]: 4
- [Counter 2]: 2
- [Counter 3]: 8
- ...
- [Counter 400]: 12
- [Element 1-5]
- [Counter 1]: 43
- [Counter 2]: 98
- [Counter 3]: 2
- ...
- [Counter 400]: 12
``` | The maximum number of columns in a regular table is 1024 (see [here](http://technet.microsoft.com/en-us/library/ms143432.aspx)), so you can't put 2,000 columns in one table.
That basically leaves two options:
1. Store each sub-element separately, with 400 columns (along with other identifing infromation, such as elemnt, data/time, and so on).
2. Use an entity-attribute-value model (EAV) model, with one row per element, sub-element, and value.
In general, I would lean toward storing one row for each sub-element. This would be especially true if the following are true:
* The columns for each sub-element represent the same thing ("have the same name").
* The columns for each sub-element have the same type.
* The sub-elements always have all 400 columns.
If the columns are typically different, then I would think about an EAV model or a hybrid model.
Whether you need separate tables for `Elements` and `Subelements` depends on how the results are going to be used. For a complete data model, you might want to include them. If you are "just" doing numerical analysis on measures in the loaded data and not using the data for other purposes (archiving, reporting), then these entities might not be necessary. | Looks like you can use an integer
I would just read and write a row at time
```
element int
subelement tinyint
counterID smallint
counterValue smallint
```
If you need to limit counterID to 1-400 you could do that with a trigger or a FK
```
select element, subelement, count(*) as count, min(counterValue ), max(counterValue )
from table
group by element, subelement
``` | Saving 400 counters into table(s)? | [
"",
"sql",
"t-sql",
"database-design",
"data-warehouse",
"business-intelligence",
""
] |
I can't seem to figure this one out. I have a table of transactions (lots of them), with date, customer ID etc.
I want to select, for a specific day, the datetime for only the first AND the last transaction for each customer on that day, like so:
```
custID FirstT LastT
318 08:05 18:35
968 03:21 13:54
488 12:34 14:28
```
SQL Server 2008. Sounds simple enough but I'm about ready to throw in the towel... Would appreciate help.. | ```
SELECT
custID,
MIN(transaction_date) AS FirstT,
MAX(transaction_date) AS LastT
FROM
yourTable
WHERE
transaction_date >= '2014-04-01'
AND transaction_date < '2014-04-02'
GROUP BY
custID
``` | Try this:
```
SELECT custid, DATEADD(dd, 0, DATEDIFF(dd, 0, date)) Date, MIN(date) FirstT, MAX(date) LastT
FROM transactions
GROUP BY custid, DATEADD(dd, 0, DATEDIFF(dd, 0, date))
``` | SQL: How can I select the first and last date for each customer? | [
"",
"sql",
"t-sql",
""
] |
There is table with maker, model and type. I should select all makers that have more than 1 model, but all are the same type
my attempt is
```
select maker, type
from product
where
((select count(model) from product) = (select count(model) from product where type='Printer')) or
((select count(model) from product) = (select count(model) from product where type='PC')) or
((select count(model) from product) = (select count(model) from product where type='Laptop'))
```
but it doesn't give correct answer. can anybody help me?
P.S. type can be only Printer, PC or Laptop | The following query will probably get you the desired result:
```
SELECT DISTINCT product.maker, product.type
FROM product
INNER JOIN
(SELECT maker, count(distinct model) model_count, count(distinct type) type_count
FROM product
GROUP BY maker
HAVING count(distinct model) > 1
AND count(distinct type) = 1
) selected_makers
ON product.maker = selected_makers.maker
ORDER BY product.maker;
```
The inline view `selected_makers` first selects the makers that have more than one model but only one type. Then, the details for these makers are obtained from the `products` table. | Try this:
```
SELECT maker
FROM PRODUCT
GROUP BY type, maker
HAVING COUNT(model)>1;
```
Also, this is the sql fiddle file <http://sqlfiddle.com/#!4/5f09a/1> | Select from table under circumstances | [
"",
"sql",
"select",
""
] |
I have a sql query, the exact code of which is generated in C#, and passed through ADO.Net as a text-based SqlCommand.
The query looks something like this:
```
SELECT TOP (@n)
a.ID,
a.Event_Type_ID as EventType,
a.Date_Created,
a.Meta_Data
FROM net.Activity a
LEFT JOIN net.vu_Network_Activity na WITH (NOEXPAND)
ON na.Member_ID = @memberId AND na.Activity_ID = a.ID
LEFT JOIN net.Member_Activity_Xref ma
ON ma.Member_ID = @memberId AND ma.Activity_ID = a.ID
WHERE
a.ID < @LatestId
AND (
Event_Type_ID IN(1,2,3))
OR
(
(na.Activity_ID IS NOT NULL OR ma.Activity_ID IS NOT NULL)
AND
Event_Type_ID IN(4,5,6)
)
)
ORDER BY a.ID DESC
```
This query has been working well for quite some time. It takes advantage of some indexes we have on these tables.
In any event, all of a sudden this query started running really slow, but ran almost instantaneously in SSMS.
Eventually, after reading several resources, I was able to verify that the slowdown we were getting was from poor parameter sniffing.
By copying all of the parameters to local variables, I was able to successfully reduce the problem. The thing is, this just feels like all kind of wrong to me.
I'm assuming that what happened was the statistics of one of these tables was updated, and then by some crappy luck, the very first time this query was recompiled, it was called with parameter values that cause the execution plan to differ?
I was able to track down the query in the Activity Monitor, and the execution plan resulting in the query to run in ~13 seconds was:

Running in SSMS results in the following execution plan (and only takes ~100ms):

### So what is the question?
I guess my question is this: How can I fix this problem, without copying the parameters to local variables, which [could lead to a large number of cached execution plans](http://www.brentozar.com/archive/2013/06/the-elephant-and-the-mouse-or-parameter-sniffing-in-sql-server/#comment-448910)?
Quote from the [linked comment / Jes Borland](http://www.brentozar.com/archive/2013/06/the-elephant-and-the-mouse-or-parameter-sniffing-in-sql-server/#comment-448910):
> You can use local variables in stored procedures to “avoid” parameter sniffing. Understand, though, that this can lead to many plans stored in the cache. That can have its own performance implications. There isn’t a one-size-fits-all solution to the problem!
My thinking is that if there is some way for me to manually remove the current execution plan from the temp db, that might just be good enough... but everything I have found online only shows me how to do this for an actual named stored procedure.
This is a text-based SqlCommand coming from C#, so I do not know how to find the cached execution plan, with the sniffed parameter values, and remove it?
Note: the somewhat obvious solution of "just create a proper stored procedure" is difficult to do because this query can get generated in a number of different ways... and would require a somewhat unpleasant refactor. | If you want to remove a specific plan from the cache then it is really a two step process: first obtain the plan handle for that specific plan; and then use DBCC FREEPROCCACHE to remove that plan from the cache.
To get the plan handle, you need to look in the execution plan cache. The T-SQL below is an example of how you could search for the plan and get the handle (you may need to play with the filter clause a bit to hone in on your particular plan):
```
SELECT top (10)
qs.last_execution_time,
qs.creation_time,
cp.objtype,
SUBSTRING(qt.[text], qs.statement_start_offset/2, (
CASE
WHEN qs.statement_end_offset = -1
THEN LEN(CONVERT(NVARCHAR(MAX), qt.[text])) * 2
ELSE qs.statement_end_offset
END - qs.statement_start_offset)/2 + 1
) AS query_text,
qt.text as full_query_text,
tp.query_plan,
qs.sql_handle,
qs.plan_handle
FROM
sys.dm_exec_query_stats qs
LEFT JOIN sys.dm_exec_cached_plans cp ON cp.plan_handle=qs.plan_handle
CROSS APPLY sys.dm_exec_sql_text (qs.[sql_handle]) AS qt
OUTER APPLY sys.dm_exec_query_plan(qs.plan_handle) tp
WHERE qt.text like '%vu_Network_Activity%'
```
Once you have the plan handle, call DBCC FREEPROCCACHE as below:
```
DBCC FREEPROCCACHE(<plan_handle>)
``` | There are many ways to [delete/invalidate a query plan](http://sqlhint.com/sqlserver/query-plan/delete-or-invalidate-query-plan):
```
DBCC FREEPROCCACHE(plan_handle)
```
or
```
EXEC sp_recompile 'net.Activity'
```
or
adding `OPTION (RECOMPILE)` query hint at the end of your query
or
using `optimize for ad hoc workloads` server settings
or
updating statistics | Parameter Sniffing causing slowdown for text-base query, how to remove execution plan? | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
"stored-procedures",
""
] |
I have a requirement to show a listing of data associated with a given widget, however I can only aggregate on the widget while it's in sequence (essentially breaking the running total when the widget changes).
Here's a bit of a break down of what I mean...
Example data:
```
ID WIDGET PART
1 A000 B22
2 A000 B23
3 A002 B24
4 A001 B25
5 A001 B26
6 A000 B27
```
Desired output:
```
WIDGET MINPART COUNT
A000 B22 2
A002 B24 1
A001 B25 2
A000 B27 1
```
In SQL Server I've tried running the following:
```
with a as (
select
WIDGET,
min(PART) over (partition by WIDGET) as MINPART,
1 tcount
from test )
select WIDGET, MINPART, sum(tcount)
from a
group by WIDGET, MINPART
```
But this just results in the usual aggregation you might expect. I.E.:
```
WIDGET MINPART COUNT
A000 B22 3
A002 B24 1
A001 B25 2
``` | Does this work for you?
```
;with x as (
select *,
lag(widget) over(order by id) as lg
from #t
),
y as (
select *, sum(case when widget<>lg then 1 else 0 end) over(order by id) as grp
from x
)
select widget, min(part), count(*)
from y
group by widget, grp
``` | @dean solution is neat but a pure SQLServer 2008 solution is possible, the idea is the same, the ranker formula
```
sum(case when widget<>lg then 1 else 0 end) over(order by id) as grp
```
can be faked by a running total, for the record the full query is
```
WITH part AS (
SELECT a.id, a.widget, a.part
, breaker = CASE WHEN a.widget<>coalesce(b.widget, a.widget)
THEN 1
ELSE 0
END
FROM Widgets a
LEFT JOIN Widgets b ON a.id = b.id + 1
)
, DATA AS(
SELECT a.id, a.widget, a.part
, rank = (SELECT sum(breaker) FROM part b WHERE a.id >= b.id)
FROM part a
)
SELECT widget
, minpart = min(part)
, [count] = count(1)
FROM DATA
GROUP BY widget, rank
``` | Grouping by an aggregate column | [
"",
"sql",
"sql-server-2008",
"t-sql",
"aggregate-functions",
"aggregate",
""
] |
I have a table "projectdetails" in which `parent_id` is the foreign key of column `project_id` in the same table..
From this below records I want only those rows whose `parent_id` does rows, does not have 'recycle\_bin` value as 1 and also should display record for creater\_id = 7923 ;
I have record like this:
```
mysql> SELECT *FROM projectdetails;
+------------+-----------------+-----------+-------------+------------+
| project_id | project_name | parent_id | recycle_bin | creater_id |
+------------+-----------------+-----------+-------------+------------+
| 0 | - | 0 | 0 | 7898 |
| 100 | Country | 0 | 2 | 7923 |
| 101 | animal | 0 | 1 | 7923 |
| 102 | India | 100 | 2 | 7923 |
| 103 | pakistan | 100 | 2 | 7923 |
| 104 | cow | 101 | 1 | 7923 |
| 105 | elephant | 101 | 1 | 7923 |
| 109 | black elephent | 105 | 1 | 7923 |
| 110 | white elephent | 105 | 2 | 7923 |
| 111 | wild black elep | 109 | 1 | 7923 |
| 112 | simple blak elp | 109 | 1 | 7923 |
| 113 | lion | 105 | 1 | 7923 |
| 114 | red lion | 113 | 1 | 7923 |
| 115 | black lion | 113 | 1 | 7923 |
| 116 | girls | 0 | 1 | 7923 |
| 117 | good girls | 116 | 1 | 7923 |
| 118 | funky girls | 116 | 1 | 7923 |
+------------+-----------------+-----------+-------------+------------+
7 rows in set (0.00 sec)
```
Expected output:
```
+------------+----------------+-----------+-------------+------------+
| project_id | project_name | parent_id | recycle_bin | creater_id |
+------------+----------------+-----------+-------------+------------+
| 100 | Country | 0 | 2 | 7923 |
| 110 | white elephent | 105 | 2 | 7923 |
+------------+----------------+-----------+-------------+------------+
```
**Note:** This is tree structure table, here on each child id user can insert many other records.. i.e same like tree structure. So please answer relevant to this note.
If you could not get what i asked for, then please write comment, I will try to explain you...
UPDATE
So basically, when query reads a row to decide whether it is applicable to show or not,
First query flow: say for country.
First look for a row say INDIA, & then next see its parent\_id, if it have parent\_id, then go to that parent\_id(now this is a project\_id=100), so next again see whether it has parent or not, if not then see column recycle\_bin .. if 1 then show this result or else ignore. | something like this? [FIDDLE](http://sqlfiddle.com/#!2/ceae3/4) for reference
```
SELECT project_id,project_name,parent_id,recycle_bin,creater_id
FROM projectdetails AS pd1
JOIN(
SELECT parent_id FROM projectdetails as pd
WHERE pd.parent_id > 0 AND pd.recycle_bin > 1
) AS t ON t.parent_id = pd1.project_id
```
---
with new data.. [NEW\_FIDDLE](http://sqlfiddle.com/#!2/33787/7)
```
SELECT
if(pd1.recycle_bin >1, pd1.project_id, t.project_id) AS project_id,
if(pd1.recycle_bin >1, pd1.project_name, t.project_name) AS project_name,
if(pd1.recycle_bin >1, pd1.parent_id, t.parent_id) AS parent_id,
if(pd1.recycle_bin >1, pd1.recycle_bin, t.recycle_bin) AS recycle_bin,
if(pd1.recycle_bin >1, pd1.creater_id, t.creater_id) AS creater_id
FROM projectdetails AS pd1
JOIN(
SELECT * FROM projectdetails AS pd
WHERE pd.parent_id > 0
AND pd.recycle_bin > 1
) AS t ON t.parent_id = pd1.project_id
GROUP BY project_id
```
---
without using IF's [LAST\_FIDDLE](http://sqlfiddle.com/#!2/d32f7/3)
```
SELECT
pd1.project_id,
pd1.project_name,
pd1.parent_id,
pd1.recycle_bin,
pd1.creater_id
FROM projectdetails AS pd1
WHERE NOT EXISTS(
SELECT pd.recycle_bin FROM projectdetails as pd
WHERE pd1.parent_id = pd.project_id
AND pd.recycle_bin > 1
) AND pd1.creater_id = 7923 and pd1.recycle_bin > 1
GROUP BY pd1.project_id;
``` | Try this query,
```
SELECT
project_id,project_name,parent_id,recycle_bin,creater_id
FROM projectdetails
WHERE recycle_bin not in (select recycle_bin from projectdetails where recycle_bin = 1 )
AND creater_id = 7923;
```
Else try this as @SamD suggested,
```
SELECT
project_id,project_name,parent_id,recycle_bin,creater_id
FROM projectdetails
WHERE recycle_bin != 1
AND creater_id = 7923;
``` | SQL : loop through same table | [
"",
"mysql",
"sql",
""
] |
I need to fetch usernames for my system, but if they exist in the table punishement\_banned, it won't fetch that username.
I have made a query which should do that work, but for some reason, the query returns 0 values.
I have 1 row in punishement\_banned with 1 name, total 2 names in the players table, so it must display 1 row.
```
SELECT players.username FROM players LEFT JOIN punishement_banned a ON a.username = players.username WHERE players.username != a.username;
```
But if I run this query, it will show the 2 names:
```
SELECT players.username FROM players LEFT JOIN punishement_banned a ON a.username = players.username;
```
What is wrong with my query? | I have created sqlfiddle: <http://www.sqlfiddle.com/#!2/fd650/4/0>
```
SELECT username
FROM players
WHERE NOT EXISTS
(
SELECT username
FROM punishement_banned
WHERE players.username = punishement_banned.username
)
``` | This should do the job:
```
SELECT username
FROM players
WHERE players.username NOT IN
(SELECT username FROM punishement_banned)
```
The problem is, you join the tables on the usernames being equal, and then exclude the usernames equal to each other. | MySQL select username only if username doesn't exist in other table | [
"",
"mysql",
"sql",
""
] |
I am trying to calculate an average based on values from 2 table columns in `MySQL`.
Lets say I have this table structure:
```
id | user_id | first_score | last_score
1 | 1 | 10 | 60
2 | 1 | 70 | 10
3 | 1 | 100 | NULL
```
What I am trying to achieve here, is calculating the AVG of the highest value (i.e. 60, 70, 100). But seeing as they are in different colums, not sure how to go about it.. | You solve this with the GREATEST function. Unfortunately it results in NULL when one or both values are NULL. So:
```
select avg( greatest( coalesce(first_score,last_score) , coalesce(last_score,first_score) ) )
from mytable;
``` | ```
select avg(GREATEST(first_score , last_score))
from the_table
``` | Calculating average from 2 database table columns | [
"",
"mysql",
"sql",
""
] |
I have a a room booking system where, a user can choose a room, and then book timeslots for that given room.
I wan't to extend my system a bit, with the option to have a top 10 list of the most booked rooms.
You can see my database, and it's foreign keys here:

I know that I can count all of my bookings that have a room\_id of 2 fx:
```
SELECT COUNT(*) FROM `bookings` WHERE `room_id` = 2
```
But what I want to achive, is having list that would look something like this:
```
Room1 = 84 bookings
Room2 = 70 bookings
Room3 = 54 bookings
etc.
```
Can anybody point me in the right direction? | ```
SELECT COUNT(*) as bCount, room_id
FROM `bookings`
GROUP BY room_id
ORDER BY bCount
LIMIT 10
``` | I think you should use GROUP BY Clause
```
SELECT Count(*) as Count , room_id
FROM bookings
GROUP BY room_id
ORDER BY Count
``` | What can I use if I want't to display a top 10 list of records | [
"",
"mysql",
"sql",
""
] |
I am trying to use if in an Oracle query .
I need something like this , But cant figure the syntax , if i can get help
```
select process
from workstep
where workstep_name = 'Manager'
and (performer != 'Test' if end_time =null). <----- this line
```
This means if endtime = null And performer ='Test' then DONT show the record; but if, for example, endTime is not null and performer = 'test' then SHOW the record. | You can't use IF in SQL with Oracle, but this is possible with simple BOOLEAN logic. You just need to negate two conditions at the same time:
```
select process
from workstep
where workstep_name = 'Manager'
and not ( performer = 'Test' and end_time is null )
``` | You can do it this way
```
and (end_time is not null or (end_time is null and performer <> 'Test'))
```
If we have datas like this (left is performer, right is end\_time)
```
'test' - notnulldate
'test' - nulldate
'tttt' - notnulldate
'tttt' - nulldate
this will return all lines except 'test'-nulldate
```
maybe you want
```
and ((end_time is not null and performer = 'Test') or (end_time is null and performer <> 'Test'))
```
which will return
```
'test'- notnulldate
'tttt'- nulldate
``` | Conditional results based on two interconnected columns | [
"",
"sql",
"oracle",
""
] |
If I want to delete some event I need to query something like
`"DROP EVENT IF EXISTS eventname"`
But I can't find the command of deleting all the events at one time,must delete event one by one.
Is there some SQL of deleting all events at one time?
```
"DROP EVENT IF EXISTS (SELECT EVENT_NAME FROM information_schema.EVENTS)"
```
is not working either. | sample one:
```
DELETE FROM mysql.event
WHERE db = 'myschema'
AND definer = 'jon@ghidora'
AND name = 'e_insert';
```
**<https://dev.mysql.com/doc/refman/5.1/en/events-privileges.html>**
if you can delete the event with `DROP EVENT IF EXISTS` and re-add it with the new scheduled time.
To permanently delete an event yourself, you can use `DROP EVENT`:
```
DROP EVENT [IF EXISTS] event_name
```
**<https://dev.mysql.com/doc/refman/5.1/en/drop-event.html>** | To construct a drop events query, you can do something like this:
```
select concat('drop event if exists ', event_name, ';') from information_schema.events;
``` | How to delete all events in MySQL | [
"",
"mysql",
"sql",
"database",
""
] |
I have the following query:
```
SELECT DATEADD(DAY, 0 - (DATEPART(weekday, GETDATE()) % 7), GETDATE())
```
Which displays:
```
2014-04-19 10:47:46.790
```
How can I modify the query so it displays `04/19/2014` or `04-19-2014` | `SELECT CONVERT(VARCHAR, DATEADD(DAY, 0 - (DATEPART(weekday, GETDATE()) % 7), GETDATE()), 101)`
**Outputs**
`04/19/2014`
And
`SELECT CONVERT(VARCHAR, DATEADD(DAY, 0 - (DATEPART(weekday, GETDATE()) % 7), GETDATE()), 110)`
**Outputs**
`04-19-2014`
Alternately, you could format this in the consuming application (in your case, SSRS). This could be done like this
```
=Format(date_column, "MM/dd/yyyy")
```
or
```
=Format(date_column, "MM-dd-yyyy")
``` | for 04/22/2014
```
select convert(varchar(10), getdate(), 101)
```
for 04-22-2014
```
select convert(varchar(10), getdate(), 110)
``` | How to format date to a certain way in SQL | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I've a basic SQL table with a simple heirarchial connection between each rows. That is there is a ParentID for Every rows and using that its connecting with another row. Its as follows
```
AccountID | AccountName | ParentID
---------------------------------------
1 Mathew 0
2 Philip 1
3 John 2
4 Susan 2
5 Anita 1
6 Aimy 1
7 Elsa 3
8 Anna 7
.............................
.................................
45 Kristoff 8
```
**Hope the structure is clear**
But my requirement of listng these is a little weird. That is when we pass an AccountID, it should list all its parents and siblings and siblings childrens. But it never list any child of that AccountID to any level. I can explain that in little more detail with a picture. Sorry for the clarity of the picture.. mine is an old phone cam..

**When we pass the AccountID 4**, it should list all Parents and its siblings, **but it should not list 4,6,7,8,9,10**. That means that account and any of it childrens should be avoid in the result (Based on the picture tree elements). Hope the explanation is clear. | If I've got it right and you need to output whole table except 4 and all of it's descendants then try this recursive query:
```
WITH CT AS
(
SELECT * FROM T WHERE AccountID=4
UNION ALL
SELECT T.* FROM T
JOIN CT ON T.ParentID = CT.AccountId
)
SELECT * FROM T WHERE AccountID
NOT IN (SELECT AccountID FROM CT)
```
`SQLFiddle demo`
Answering to the question in the comment:
> So it will not traverse to the top. It only traverse to specified
> account. For example if I pass 4 as first parameter and 2 as second
> parameter, the result should be these values 2,5,11,12
You should start from the ID=2 and travel to the bottom exclude ID=4 so you cut whole subtree after ID=4:
```
WITH CT AS
(
SELECT * FROM T WHERE AccountID=2
UNION ALL
SELECT T.* FROM T
JOIN CT ON T.ParentID = CT.AccountId
WHERE T.AccountId<>4
)
SELECT * FROM CT
``` | Try this:
```
;with cte as
(select accountid,parentid, 0 as level from tbl
where parentid = 0
union all
select t.accountid,t.parentid,(level+1) from
cte c inner join tbl t on c.accountid= t.parentid
)
select * from cte
where level < (select level from cte where accountid = @accountid)
```
When you pass in the parameter `@accountid` this will return the `accountid` values of all nodes on levels before that of the parameter.
If you want to return everything on the same level as input except input itself, you can change the `where` clause to;
```
where level <=(select level from cte where accountid= @accountid )
and accountid <> @accountid
```
In your example, if `@accountid` = 4, this will return the values 1,2,3 (ancestors) as well as 5,13,14 (siblings). | Query to List all hierarchical parents and siblings and their childrens, but not list own childrens | [
"",
"sql",
"sql-server",
""
] |
I know this question has been asked and answered. I understand the problem and I understand the underlying cause and I understand the solution. What I DON'T understand is how to implement the solution.
I'll try to be detailed....
**Background:** Each material is being grouped on `WellID` (I work in oil and gas) and `SandType` which is my primary key in each table, these come from 2 lookup tables one for each. (I work in oil and gas)
I have 3 tables that store material (sand)) weights at 3 different stages in the job process. Basically the weight from the engineer's DESIGN, what was DELIVERED and what is in INVENTORY.
I know that the join is messed up and adding the total for each row in each table. Sometimes double triple etc.
I am grouping on `WellID` and `SandID`.
Now I don't want someone to do the work for me. I just don't know how or where in access to restrict it to what I want, or if modifying t he sql the proper way to write the code. Current work around is 3 separate sum queries one for each table, but that is going to get inefficient and added steps.
My whole database purpose and subsequent reports hinge off math on these 3 numbers so, my show stopper here is putting the fat lady on stage, and is about to become a deal breaker at the end of the line! 0
I need some advice, direction, criticism, wisdom, witty euphemisms or a new job!
The 3 tables look as follows
```
Design:
T_DESIGN
DesignID WellID Sand_ID Weight_DES Time_DES
89 201 1 100 4/21/2014 6:46:02 AM
98 201 2 100 4/21/2014 7:01:22 AM
86 201 4 100 4/21/2014 6:28:01 AM
93 228 5 100 4/21/2014 6:53:34 AM
91 228 1 100 4/21/2014 6:51:23 AM
92 228 1 100 4/21/2014 6:53:30 AM
Delivered:
T_BOL
BOLID WellID_BOL SandID_BOL Weight_BOL
279 201 1 100
280 201 1 100
281 228 2 5
282 228 1 10
283 228 9 100
Inventory:
T_BIN
StrapID WellID_BIN SandID_BIN Weight_BIN
11 201 1 100
13 228 1 10
14 228 1 0
17 228 1 103
19 201 1 50
```
The Query Results:
```
Test Query99
WellID
WellID SandID Sum Of Weight_DES Sum Of Weight_BOL Sum Of Weight_BIN
201 1 400 400 300
228 1 600 60 226
```
SQL:
```
SELECT DISTINCTROW L_WELL.WellID, L_SAND.SandID,
Sum(T_DESIGN.Weight_DES) AS [Sum Of Weight_DES],
Sum(T_BOL.Weight_BOL) AS [Sum Of Weight_BOL],
Sum(T_BIN.Weight_BIN) AS [Sum Of Weight_BIN]
FROM ((L_SAND INNER JOIN
(L_WELL INNER JOIN T_DESIGN ON L_WELL.[WellID] = T_DESIGN.[WellID_DES])
ON L_SAND.SandID = T_DESIGN.[SandID_DES])
INNER JOIN T_BIN
ON (L_WELL.WellID = T_BIN.WellID_BIN)
AND (L_SAND.SandID = T_BIN.SandID_BIN))
INNER JOIN T_BOL
ON (L_WELL.WellID = T_BOL.WellID_BOL) AND (L_SAND.SandID = T_BOL.SandID_BOL)
GROUP BY L_WELL.WellID, L_SAND.SandID;
```
Two LooUp tables are for Well Names and Sand Types. (Well has been abbreviate do to size)
L\_Well:
```
WellID WellName_WELL
3 AAGVIK 1-35H
4 AARON 1-22
5 ACHILLES 5301 41-12B
6 ACKLINS 6092 12-18H
7 ADDY 5992 43-21 #1H
8 AERABELLE 5502 43-7T
9 AGNES 1-13H
10 AL 5493 44-23B
11 ALDER 6092 43-8H
12 AMELIA FEDERAL 5201 41-11B
13 AMERADA STATE 1-16X
14 ANDERSMADSON 5201 41-13H
15 ANDERSON 1-13H
16 ANDERSON 7-18H
17 ANDRE 5501 13-4H
18 ANDRE 5501 14-5 3B
19 ANDRE SHEPHERD 5501 14-7 1T
```
Sand Lookup:
LSand
```
SandID SandType_Sand
1 100 Mesh
2 20/40 EP
3 20/40 RC
4 20/40 W
5 30/50 Ceramic
6 30/50 EP
7 30/50 RC
8 40/70 EP
9 40/70 W
10 NA See Notes
``` | # Querying and Joining Aggregation Data through an MS Access Database
I noticed your concern for pointers on how to implement some of the theory behind your aggregation queries. While SQL queries are good power-tools to get to the core of a difficult analysis problem, it might also be useful to show some of the steps on how to bring things together using the built-in design tools of MS Access.
> This solution was developed on MS Access 2010.
**Comments on Previous Solutions**
[@xQbert](https://stackoverflow.com/users/1016435/xqbert) had a solid start with the following SQL statement. The sub query approach could be visualized as individual query objects created in Access:
```
FROM
(SELECT WellID, Sand_ID, Sum(weight_DES) as sumWeightDES
FROM T_DESGN) A
INNER JOIN
(SELECT WellID_BOL, Sum(Weight_BOL) as SUMWEIGHTBOL
FROM T_BOL B) B
ON A.Well_ID = B.WellID_BOL
INNER JOIN
(SELECT WellID_BIN, sum(Weight_Bin) as SumWeightBin
FROM T_BIN) C
ON C.Well_ID_BIN = B.Well_ID_BOL
```
Depending on the actual rules of the business data, the following assumptions made in this query may not necessarily be true:
* Will the tables of `T_DESIGN`, `T_BOL` and `T_BIN` be populated at the same time? The sample data has mixed values, i.e., there are `WellID` and `SandID` combinations which do not have values for all three of these categories.

* `INNER` type joins assume all three tables have records for each dimension value (Well-Sand combination)
[@Frazz](https://stackoverflow.com/users/876610/frazz) improved on the query design by suggesting that whatever is selected as the "base" joining table (`T_DESIGN` in this case), this table must be populated with all the relevant dimensional values (`WellID` and `SandID` combinations).
```
SELECT
WellID_DES AS WellID,
SandID_DES AS SandID,
SUM(Weight_DES) AS Weight_DES,
(SELECT SUM(Weight_BOL) FROM T_BOL WHERE T_BOL.WellID_BOL=d.WellID_DES
AND T_BOL.SandID_BOL=d.SandID_DES) AS Weight_BOL,
(SELECT SUM(Weight_BIN) FROM T_BIN WHERE T_BIN.WellID_BIN=d.WellID_DES
AND T_BIN.SandID_BIN=d.SandID_DES) AS Weight_BIN
FROM T_DESIGN;
(... note: a group-by statement should be here...)
```
* This was animprovement because now all joins originate from a single point. If a key-value does not exist in either `T_BOL` or `T_BIN`, results will still come back and the entire record of the query would not be lost.
* Again, it may be possible that there are no `T_DESIGN` records matching to values stored in the other tables.
## Building Aggregation Sub Query Objects
The presented data does not suggest that there is any direct interaction between the data in each of the three tables aside from lining up their results in the end for presentation based on a common key-value pair (`WellID` and `SandID`). Since we are using Access, there is a chance to do these calculations separately.

This query was designed using the "summarizing" feature of the Access query design tool. It's output, after pointing to the `T_DESIGN` table looked like this:

## Making Dimension Table Through a Cartesian Product
There are mixed opinions out there about [cartesian products](http://www.databasejournal.com/features/msaccess/article.php/3839466/Uses-for-Cartesian-Products-in-MS-Access.htm), but they do actually have a purpose.
Most of the concern is that a runaway cartesian product query will make millions and millions of nonsensical data values. In this query, it's specifically designed to simulate a real business condition.
**The Case for a Cartesian Product**
Picking from the sample data provided:
* Some of the **Sand Types**: "20/40 EP", "30/50 Ceramic", "40/70 EP", and "30/50 RC" that are moved between their respective wells, are these sand types found at these wells consistently throughout the year?

* Without an anchoring dimension for the key-values, Wells would not be found anywhere in the database via querying. It's not that they do not exist... it's just that there is no recorded data (i.e., Sand Type Weights delivered) for them.
**A Reference Dimension Query Product**
A dimension query is simple to produce. By referencing the two sources of keys: `L_WELL` and `L_SAND` (both look up tables or dimensional tables) without identifying a join condition, all the different combinations of the two key-values (WellID and SandID) are made:

The shortcut in SQL looks like this:
```
SELECT L_WELL.WellID, L_SAND.SandID, L_WELL.WellName, L_SAND.SandType
FROM L_SAND, L_WELL;
```
The resulting data looks like this:

Instead of using any of the operational data tables: `T_DESIGN`, `T_BOL`, or `T_BIN` as sources of data for a static dimension such as a list of Oil Wells, or a catalog of Sand Types, that data has been predetermined and can even be transferred to a real table since it probably will not change much once it is created.
## Correlating Sub Query Results from Different Sources
After repeating the process and creating the summary tables for the other two sources (`T_BOL` and `T_BIN`), You can finally arrange the results through a simple query and join process.
The actual JOIN operations are between the dimension table/query: `QSUB_WELL_SAND` and all three of the summary queries: `QSUB_DES`, `QSUB_BOL`, and `QSUB_BIN`.
I have chosen to chosen to implement `LEFT OUTER` joins. If you are not sure of the difference between the different "outer" joins, this is the choice I made through the Access Query Design dialogue:

`QSUB_WELL_SAND` is defined as our anchor dimension. It will always have more records than any of the other tables. An `OUTER JOIN` should be defined to KEEP all reference dimension records... and all Summary Table query results, regardless if there is a match between the two Query results.
**QSUB\_WEIGHTS/ The Query to Combine All Sub Query Results**
This is what the design of the final output query looks like:

This is what the data output looks like when this query design is executed:

## Conclusions and Clean Up: Some Closing Thoughts
With respect to the join to the dimension query, there is a lot of empty space where there are no records or data to report on. This is where a cleverly placed filter or query criteria can shrink the output to exactly what you care to look at the most. Here's how mine looked after I added additional ending query criteria:

My data was based on what was supplied by the OP, except where the ID's assigned to the `Well Type` attribute did not match the sample data. The values I assigned instead are posted below as well.
Access supports a different style of database operations. Step-wise queries can be developed to hold pre-processed, special sets of data that can be reintroduced to the other data tables and query results to develop complex query criteria.
All this being said, ***Programming in SQL can also be just as rewarding.*** Be sure to explore some of the differences between the results and the capabilities you can tap into by using one approach (sql coding), the other approach (access design wizards) or *both* of the approaches. There's definitely a lot of room to grow and discover new capabilities from just the example provided here.
Hopefully I haven't stolen all the fun from developing a solution for your situation. I read into your comment about "building more on top" as the harbinger of more fun to come, so I don't feel so bad...! Happy Developing!
**Data Modifications from the Sample Set**
 | I would simplify it excluding L\_WELL and L\_SAND. If you are just interestend in IDs, then they really shouldn't be necessary joins. If all the other 3 tables have the WellID and SandID columns, then pick the one that is sure to have all combos.
Supposing it's the Design table, then:
```
SELECT
WellID_DES AS WellID,
SandID_DES AS SandID,
SUM(Weight_DES) AS Weight_DES,
(SELECT SUM(Weight_BOL) FROM T_BOL WHERE T_BOL.WellID_BOL=d.WellID_DES AND T_BOL.SandID_BOL=d.SandID_DES) AS Weight_BOL,
(SELECT SUM(Weight_BIN) FROM T_BIN WHERE T_BIN.WellID_BIN=d.WellID_DES AND T_BIN.SandID_BIN=d.SandID_DES) AS Weight_BIN
FROM T_DESIGN
GROUP BY WellID, SandID;
```
... and make sure all your tables have an index on WellID and SandID.
Just to be clear. I dont' think it's a good idea to start the join from the lookup tables, or from their cartesian product. You can always left join them to fetch descriptions and other data. But the main query should be the one with all the combos of WellID and SandID... or if not all, at least the most. Things get difficult if none of the 3 tables (DESIGN, BOL and BIN) have all combos. In that case (and I'd say only in that case) then you might as well start with the cartesian product of the two lookup tables. You could also do a UNION, but I doubt that would be more efficient. | Access 2010 doubling the sum in query | [
"",
"sql",
"database",
"join",
"ms-access-2010",
""
] |
```
SELECT *, DATEDIFF(CURDATE(),tarikhmohon) AS hari
FROM mohon a
INNER JOIN tblstatus_tak_lengkap b on a.noMyKid=b.nomykid
WHERE noMyKid=130902100437
```
I have tried that SQL but I got an error.
> #1052 - Column 'noMyKid' in where clause is ambiguous.
I can't find the problem. | Column `noMyKid` is present is both tables. You should tell the server on what table the column you want to filter, eg
```
WHERE a.noMyKid = 130902100437
```
or
```
WHERE b.noMyKid = 130902100437
```
Whatever you use, it doesn't matter since you are using `INNER JOIN`. | I think you have the column "noMyKid" in both tables.
Prefix it like this : a.noMyKid | #1052 - Column 'noMyKid' in where clause is ambiguous | [
"",
"sql",
"database",
"mysql-error-1052",
""
] |
If I do:
```
ALTER TABLE testtable MODIFY mycolumn NEWDATATYPE;
```
I loose other definitions like NOT NULL, COMMENTS, DEFAULT values... Is there a way to do it?
[In PostgreSQL I used](http://www.postgresql.org/docs/9.3/static/ddl-alter.html#AEN2790):
```
ALTER TABLE testtable ALTER COLUMN mycolumn NEWDATATYPE;
```
And it does what is supposed to: change the column datatype, without touching any other definition, only giving error if data types were not compatible and so on (but you can specify USING).
I'll try a workaround, but I did a query to identify several columns across different tables to update the datatype and now I've identified that this data was lost, so I'll have to redo it considering these informations too. | As it's stated in [manual page](http://dev.mysql.com/doc/refman/5.0/en/alter-table.html), `ALTER TABLE` requires all new type attributes to be defined.
However, there is a way to overcome this. You may use [`INFORMATION_SCHEMA` meta-data](https://dev.mysql.com/doc/refman/5.0/en/information-schema.html) to reconstruct desired `ALTER` query. for example, if we have simple table:
```
mysql> DESCRIBE t;
+-------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+------------------+------+-----+---------+----------------+
| id | int(11) unsigned | NO | PRI | NULL | auto_increment |
| value | varchar(255) | NO | | NULL | |
+-------+------------------+------+-----+---------+----------------+
2 rows in set (0.01 sec)
```
then we can reproduce our alter statement with:
```
SELECT
CONCAT(
COLUMN_NAME,
' @new_type',
IF(IS_NULLABLE='NO', ' NOT NULL ', ' '),
EXTRA
) AS s
FROM
INFORMATION_SCHEMA.COLUMNS
WHERE
TABLE_SCHEMA='test'
AND
TABLE_NAME='t'
```
the result would be:
```
+--------------------------------------+
| s |
+--------------------------------------+
| id @new_type NOT NULL auto_increment |
| value @new_type NOT NULL |
+--------------------------------------+
```
Here I've left `@new_type` to indicate that we can use variable for that (or even substitute our new type directly to query). With variable that would be:
* Set our variables.
```
mysql> SET @new_type := 'VARCHAR(10)', @column_name := 'value';
Query OK, 0 rows affected (0.00 sec)
```
* Prepare variable for [prepared statement](http://dev.mysql.com/doc/refman/5.0/en/sql-syntax-prepared-statements.html) (it's long query, but I've left explanations above):
```
SET @sql = (SELECT CONCAT('ALTER TABLE t CHANGE `',COLUMN_NAME, '` `', COLUMN_NAME, '` ', @new_type, IF(IS_NULLABLE='NO', ' NOT NULL ', ' '), EXTRA) AS s FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='test' AND TABLE_NAME='t' AND COLUMN_NAME=@column_name);
```
* Prepare statement:
```
mysql> prepare stmt from @sql;
Query OK, 0 rows affected (0.00 sec)
Statement prepared
```
* Finally, execute it:
```
mysql> execute stmt;
Query OK, 0 rows affected (0.22 sec)
Records: 0 Duplicates: 0 Warnings: 0
```
Then we'll get our data type changed to `VARCHAR(10)` with saving all the rest specifiers:
```
mysql> DESCRIBE t;
+-------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+------------------+------+-----+---------+----------------+
| id | int(11) unsigned | NO | PRI | NULL | auto_increment |
| value | varchar(10) | NO | | NULL | |
+-------+------------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)
``` | ```
ALTER TABLE tableName
MODIFY COLUMN columnName datatype
``` | Change column data type in MySQL without losing other metadata (DEFAULT, NOTNULL...) | [
"",
"mysql",
"sql",
""
] |
I've been replacing a set of CLR stored procedures with straight SQL but I've been stuck on this one report.
The system makes entries into a stats table when an event occurs. If a particular event doesn't occur, there is no entry in the HourlyStats table.
```
Table HourlyStats
UserID TimeStamp EventID Duration
1 (datetime) 5 36
2 (datetime) 1 259
1 (datetime) 2 72
3 (datetime) 5 36
```
Let's say there are 5 different eventID's in a table Categories
```
Table Categories
EventID Description
1 Break
2 Supervision
3 Lunch
4 Outbound
5 Inbound
```
There is also a table of Users
```
Users
UserID Name
1 Tom
2 Mary
3 George
4 Carly
```
and the output has to look like:
```
UserID Description Sum(TimeSec)
Tom Break Null
Tom Supervision 72
Tom Lunch Null
Tom Outbound Null
Tom Inbound 36
Mary Break 259
```
I've tried a variety of joins but don't get the results I'm looking for.
It may be that I can't do this directly via a single query. My next approach is to construct a temp table structured like the Output table but with NULL values for the SUM column and then update the table with results.
I've tried many variations. Here is where I started
```
SELECT HourlyStats.UserID, Categories.Description, SUM(HourlyStats.Duration) AS Expr1
FROM Categories FULL OUTER JOIN
HourlyStats ON Categories.EventID = HourlyStats.EventID
Group by UserID, Description
Order by UserID
```
Any suggestions? | Here you go:
```
SELECT u.Name, c.[Description], hs.Duration
FROM Users u
CROSS JOIN Categories c
LEFT OUTER JOIN HourlyStats hs
ON u.UserID = hs.UserID
AND c.EventID = hs.EventID
``` | What you need is `CROSS JOIN` to get every possible combination of `USERS` and `EVENTS` and than `LEFT` join to `HourlyStats` code will be like this
```
;WITH base
AS (
SELECT u.UserID
,u.name
,c.EventId
,c.Description
FROM Categories AS c
CROSS JOIN Users AS u
)
SELECT b.name
,b.Description
,SUM(hs.Duration) OVER ( PARTITION BY hs.UserId, hs.EventID ) AS SumTime
FROM Base AS b
LEFT JOIN hourlyStats AS hs
ON b.UserID = hs.UserId
AND b.EventId = hs.EventID
ORDER BY 1 DESC
,2 ASC
``` | SQL Query needs to return rows even when results are null | [
"",
"sql",
"sql-server-2008",
"join",
""
] |
Can we set isolation level for plain SQL statements in a stored procedure in SQL Server 2005/2008?
Case 1: (This will work fine)
```
CREATE PROCEDURE MySP
AS
BEGIN
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN TRAN
SELECT * FROM MyTable
COMMIT TRAN
END
```
Case 2: (does this isolation stuff work here?)
```
CREATE PROCEDURE MySP
AS
BEGIN
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SELECT * FROM MyTable
END
```
If case 2 is correct, would it work for several select statements as well? | If you use `SET TRANSACTION ISOLATION LEVEL` in a stored procedure, this transaction isolation level is used for the duration of the stored proc. According to [MSDN](http://technet.microsoft.com/en-us/library/ms173763.aspx):
> If you issue SET TRANSACTION ISOLATION LEVEL in a stored procedure or trigger, when the object returns control the isolation level is reset to the level in effect when the object was invoked.
Setting transaction isolation level is not the same as starting a transaction. Transaction isolation level tells SQL Server how to control locking.
If you only have multiple SELECT queries with READ UNCOMMITTED transaction isolation level, putting them all into a transaction won't make practical difference. | Yes it will work for multiple select statements.
If you are worried about the lack if a transaction in the second stored procedure you should know that the query is executed under an implicit transaction as opposed to an explicit transaction that you have in the first stored procedure. | Transaction isolation for sql statements | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have a database table in the format:
```
DataA | DataB | DataC | TimeStamp | UniqueID
```
Data may look like:
```
5 | 4 | 11 | 1/1/2014 | 1
5 | 4 | 2 | 2/1/2014 | 2
5 | 4 | 11 | 3/1/2014 | 3
3 | 6 | 7 | 4/1/2014 | 4
```
The problem is that I have duplicate entries where DataA-C are all the same (rows 1 and 3), but the TimeStamp (date data was recorded) and UniqueID are always different. The way that I am recording data (I do not have the option to change recording procedures) always leaves open the possibility of recording the same data twice.
How can I run a query that compares all of the Data columns to check if there is a duplicate row and remove the entry with the latest data. For instance row 1 was recorded first so I would want to remove row 3 and keep row 1
Thank in advance for your help.
Here is an option I have tried:
```
Select Line
DataA
, DataB
, DataC
FROM [Database].[dbo].[tbl_Data]
Where Line = 5
Group
BY Line
DataA
, DataB
, DataC
Having COUNT(*) > 1
``` | ```
DELETE FROM the_table
WHERE id IN (the select to return duplicated records' ids)
```
The select should be similar to this one
```
SELECT
id
FROM
the_table T JOIN
(
SELECT MIN(id) AS id FROM the_table
GROUP BY all your fields here
) sub ON T.id= SUB.id
``` | ```
DELETE FROM test
WHERE UniqueId NOT IN (SELECT UniqueId FROM
(SELECT *
FROM test
ORDER BY TimeStamp) T1
GROUP BY DataA, DataB, DataC)
```
**[Fiddle](http://sqlfiddle.com/#!2/884ab2/12)** | MySQL Query Remove Duplicate Row | [
"",
"mysql",
"sql",
"database",
"duplicates",
""
] |
I have a table with a Comments field and I want to capitalize the first letter of the string in each record eg change 'duplicate' into 'Duplicate'. Some records will already have a capital at the start, and some may even be a number.
I tried this
```
SELECT UPPER(LEFT(Comments,1))+SUBSTRING(Comments,2,LEN(Comments)) FROM dbo.Template_Survey
```
but it fails because my field is an 'ntext' type.
It would also be useful to be able to capitalize the first letter after a full stop (period) but this is not essential unless someone has the code already written.
Thanks in advance. | Cast your ntext to nvarchar(max) and do the upper and left operations. Sample below.
```
SELECT UPPER(LEFT(cast(Comments as nvarchar(max)),1)) +
LOWER(SUBSTRING(cast(Comments as nvarchar(max)),2,
LEN(cast(Comments as nvarchar(max)))))
FROM dbo.Template_Survey;
```
Following should work for update.
```
Update dbo.Template_Survey SET Comments =
UPPER(LEFT(cast(Comments as nvarchar(max)),1)) +
LOWER(SUBSTRING(cast(Comments as nvarchar(max)),2,
LEN(cast(Comments as nvarchar(max)))));
``` | Cast you column to nvarchar(max)
here is the working example
<http://sqlfiddle.com/#!3/5dd26/3>
To update records you can use:
```
Update dbo.Template_Survey
set Comments = UPPER(LEFT(cast(Comments as nvarchar(max)),1)) +
LOWER(SUBSTRING(cast(Comments as nvarchar(max)),2,
LEN(cast(Comments as nvarchar(max)))))
``` | How to capitalize the first letter of a record in SQL | [
"",
"sql",
"sql-server-2008",
""
] |
I have a table1 contains 4 columns
```
AssociateId, chk1, chk2, chk3
```
and another table(table2) contains same 4 columns.
```
chk1, chk2, chk3
```
1. Columns will have the values 'yes/no/null'
2. If table1 contains 3 records and 2 records contains the value 'yes' for all chk1,chk2,chk3 columns, then both records have to be inserted into table2
3. Furthermore, these 2 records should be removed from table 1.
How is it possible using SQL Server 2008? | if i have unterstand your question right, i think this could work for you:
for the insert in table1 you can run this sql statement:
insert into table2 chk1,chk2, chk3
values (select chk1,chk2, chk3 from table 1 where chk1='yes' and chk2='yes' and chk3='yes')
and the you delete the records in table1
delete from table1 where chk1='yes' and chk2='yes' and chk3='yes' | You can use a transaction. First insert your records in table2 like
```
Insert into table2 (column1,column2,column3)
select column1, column2,column3 from table1
where column1 ='YES' and column2 ='YES' and column3 ='YES';
```
you can then delete your records from table1 based on same condition & commit your transaction. | How to copy records to another table based on a condition? | [
"",
"sql",
"sql-server",
"sql-server-2008",
"triggers",
""
] |
```
CREATE TABLE IF NOT EXISTS test (col1 INT, col2 INT);
ALTER TABLE test ADD INDEX idx_col1(col1);
ALTER TABLE test ADD INDEX idx_col2(col2);
EXPLAIN SELECT * FROM test WHERE col1>=0 AND col2<=2;
```
Result:
```
id select_type table type possible_keys key key_len ref
1 SIMPLE test range idx_col2,idx_col1 idx_col2 5 1
```
Why only use idx\_col2, not use both. | This is a classic problem concerning selects which involve ranges.
The result of an index lookup is one or more rows in a table. When SQL decides how to process your select, it has to decide what index to use first. In your case it was idx\_col2. As a result it will know all rows which satisfy (col2<=2).
From these rows it has to remove the ones which do no satisfy (col1>=0). However the index idx\_col1 is of not much help here, because it refers to the *whole table* and not just to the rows which are still in question. An index range scan on idx\_col1 would return *all* rows which satisfy the predicate and SQL would have to find rows which are found *both* by the col1 *and* col2 index range scan.
In virtually all cases this doesn't pay. If the number of rows returned from the col2 scan is small, then SQL might as well go through all these rows and check for (col1>=0) without using an index. If the number of rows is large, finding matching rows will be costly. It will have to consider all the rows returned from the col2 scan and check if there is a matching row in the col1 scan. This is more expensive than simply checking if they satisfy (col1>=0).
In general regular b-tree Indexes and ranges (concerning different columns) do not play together well. Some RDBMSs have a special kind of "spatial" index which allows efficient queries, which involve ranges. | I think, if you use both it need to be sort twice,
it sort by col2, thus the remain lines are check line by line for col1,
Maybe this is because your rows are too small, if there are many rows, it might do sort twice, thus use 2 index.
I am not sure, just wondering. | Why not use two indexes in the following sql | [
"",
"mysql",
"sql",
""
] |
i want to select a column but with diferent order :
i have 2 table :
table\_name:
```
+------+-----------+
| id | name |
+------+-----------+
| 1 | Sindra |
| 2 | Auli |
| 3 | Brian |
| 4 | Bina |
| 5 | zian |
| 6 | Bri |
| 7 | Andre |
+------+-----------+
```
table\_temp, id\_temp\_name foreign key of id(table\_name) :
```
+------+--------------+
| id | id_temp_name |
+------+--------------+
| 1 | 1 |
| 2 | 3 |
| 3 | 4 |
| 4 | 2 |
+------+--------------+
```
with this query :
```
SELECT table_name.id,table_name.name
FROM table_name JOIN table_temp ON table_name.id= table_temp.id_temp_name
ORDER BY table_temp.id_temp_name
```
i was looking for result that exactly same with id\_temp\_name order , but it showing value that not in to table\_temp to order by asc ,so the result will be :
```
+------+-----------+
| id | name |
+------+-----------+
| 1 | Sindra |
| 3 | Brian |
| 4 | Bina |
| 2 | Auli |
| 7 | Andre |
| 6 | Bri |
| 5 | zian |
+------+-----------+
```
thanks for any advice, . | Now, I tried so many times, and I could find queries that displays result exactly same as you needed. But work has to be done in two steps with an assumption that `id`s can't be negative.
Step-1: Create a valuable:
```
mysql> SET @max_id = (SELECT MAX(id) FROM table_name) * 2;
Query OK, 0 rows affected (0.00 sec)
```
Step-2: A nested Query that use above variable:
```
mysql> SELECT a.id,
-> a.name
-> FROM (
-> SELECT t.id as `id`,
-> t.name as `name`,
-> IF(t2.id, t2.id, @max_id := @max_id - 1) as `id2`
-> FROM table_name t
-> LEFT OUTER JOIN table_temp t2
-> ON t.id= t2.id_temp_name
-> GROUP BY t.id
-> ORDER BY CASE WHEN t2.id THEN t2.id
-> ELSE -t.id END
-> ) as a
-> ORDER BY a.id2;
+------+--------+
| id | name |
+------+--------+
| 1 | Sindra |
| 3 | Brian |
| 4 | Bina |
| 2 | Auli |
| 7 | Andre |
| 6 | Bri |
| 5 | zian |
+------+--------+
7 rows in set (0.00 sec)
```
Check it working @ [SQL Fiddle](http://sqlfiddle.com/#!2/ad625/1).
The logic is very simple, I used a bit math, and added new `Id` on the fly in inner SQL query. I used `max_id` variable twice of max value of present id in table\_name purpose fully because I am generating `id` that should be grater than max and in decreasing order (I did subtraction).
Give it a try!! | **AFTER EDIT 1:**
You can proceed to [this\_way](https://stackoverflow.com/users/3146681/walk-this-way)
```
SELECT tgejala.id_gejala,tgejala.nama_gejala
FROM tgejala
LEFT JOIN ttemp ON tgejala.id_gejala= ttemp.idtemp_gejala
ORDER BY CASE WHEN ttemp.id_temp is NULL THEN 1 ELSE 0 END
```
**EDIT 2:**
Ok then see the below this would work
```
SELECT tgejala.id_gejala,tgejala.nama_gejala
FROM tgejala
LEFT JOIN ttemp ON tgejala.id_gejala= ttemp.idtemp_gejala
ORDER BY CASE WHEN ttemp.id_temp is NULL THEN 1 ELSE 0 END, table_name.id desc
```
This will give you the following result
```
+------+-----------+
| id | name |
+------+-----------+
| 1 | Sindra |
| 3 | Brian |
| 4 | Bina |
| 2 | Auli |
| 7 | Andre |
| 6 | Bri |
| 5 | zian |
+------+-----------+
``` | SQL : Select statement order by other table | [
"",
"mysql",
"sql",
""
] |
Suppose I have a parameter @UserID, it can be 0 (no userid assigned) or id itself.
The structure of query is as follows
```
if @UserID > 0
select ...
where UserID=@UserID
...
else if @UserID = 0
select ...
where ...
```
What I want is the following structure
```
select ...
where if @UserID >0 then UserID = @UserID else disregard this condition
...
```
Thanks | set null as parameter value instead of 0 (zero)
```
declare @id int
set @id = null
select *
from users
where (id = @id)
or (@id is null)
``` | Use a case statement as:
```
WHERE 1 = CASE
WHEN @UserID >0 and UserID = @UserID THEN 1
ELSE 0
END
``` | Not taking into account condition | [
"",
"sql",
"sql-server",
""
] |
Morning- I am having a bit of a problem today getting a NOT filter to work in SQL 2012.
I have a list of 6030 records, and am filtering by a field called mat\_ref. There are particular names that I do not want to have in the resulting dataset. So I filtered as follows:
```
SELECT mat_ref AS [Client Name], ccode
FROM lntmu11.matter
WHERE (mat_ref <> 'McAdams')
```
And this works fine. But the moment that I add in more variables to the WHERE statement, I get no change. The number of records does not change, despite the fact that I know this field has both a Thompson and a McAdams value.
```
SELECT mat_ref AS [Client Name], ccode
FROM lntmu11.matter
WHERE (mat_ref <> 'McAdams') OR
(mat_ref = 'Thompson')
```
Any thoughts? | Do the filtering using `not in`:
```
SELECT mat_ref AS [Client Name], ccode
FROM lntmu11.matter
WHERE mat_ref NOT IN ('McAdams', 'Thompson');
``` | This is Boolean logic rather than anything else. You're searching for rows where
```
mat_ref is NOT EQUAL to McAdams
OR
mat_ref is EQUAL to Thompson
```
This will return every row as McAdams is not equal to Thompson.
I think you wanted to use AND and a not equals.
```
WHERE mat_ref <> 'McAdams'
AND mat_ref <> 'Thompson'
```
This is equivalent to:
```
WHERE NOT ( mat_ref = 'McAdams' OR mat_ref = 'Thompson' )
```
Alternatively you could use NOT IN:
```
WHERE mat_ref NOT IN ('McAdams', 'Thompson')
``` | Does the NOT function in SQL only allow one possible factor? | [
"",
"sql",
"t-sql",
""
] |
i am trying to do an
```
INSERT INTO MYTBL
VALUES (CAST(SPACE(7997) + 'abcd' as nvarchar(max))
```
and it does not go over 8000 bytes
not sure what it is i am doing wrong
MYTBL only has one column (Col1 (nvarchar(max)) | based on your code you are missing last ")"
modify your code to this:
```
INSERT INTO MYTBL
VALUES (CAST(SPACE(7997) + 'abcd' as nvarchar(max)))
```
additionaly just like @datagod said you need to convert/cast your strings as `NVARCHAR(max)` before concatenation.
you can use this
```
INSERT INTO MYTBL
VALUES ( CONVERT(NVARCHAR(MAX), SPACE(7997)) + CONVERT(NVARCHAR(MAX), 'abcd') )
``` | Try casting each of your strings as nvarchar(max) first, then concatenate them. I have found that string functions such as replicate() return regular varchar results which get truncated after 8000 chars. | SQL: trying to insert large string into varchar(max) | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have a database table as follows:
```
ProductDetails
-----------------
ProductDetailsID int
ProductIdentifier VARCHAR (20)
ProductID int
ProductFile VARCHAR(255)
ProductAvailability char(2)
RightsCountry varchar(MAX)
Deleted bit
```
There was a bug in the platform recently that allowed a large number of duplicates in. So I could have multiple ProductDetails entries which are the same EXCEPT for the ProductDetailsID (PK) and ProductFile (this is null, for some reason the duplicates didn't insert the files).
I need to write a T-SQL script that finds these duplicates with a view to deleting them (after examination).
I have found this online, which is great. It gives me the ProductIdentifier with several records, and the number of duplicates.
```
SELECT pd.ProductIdentifier, COUNT(pd.ProductIdentifier) AS NumOccurrences
FROM dbo.ProductDetails pd
GROUP BY pd.ProductIdentifier
HAVING ( COUNT(pd.ProductIdentifier) > 1 )
```
The thing is, some of these records should remain. I need to select the ProductDetail records that have duplicate ProductIdentifiers, where at least 1 of the duplicates has a FileName and all other columns are exactly the same. For example, if I have a dataset as follows:
```
ProductDetailsID | ProductIdentifier | ProductID | ProductFile | ProductAvailability | RightsCountry | Deleted
123 | 567890 | 12 | filename.png | 20 | AU CX CC CK HM NZ NU NF TK | 0
124 | 567890 | 12 | (NULL) | 20 | AU CX CC CK HM NZ NU NF TK | 0
125 | 567890 | 12 | (NULL) | 20 | AU CX CC CK HM NZ NU NF TK | 0
```
I need to return ProductDetailsID 124 and 125 as these are for deletion. I'd appreciate any guidance or links to examples or any help at all! | This works and is a cheeky way of abusing the partitioned window functions:
```
declare @ProductDetails table(
ProductDetailsID int not null,
ProductIdentifier VARCHAR(20) not null,
ProductID int not null,
ProductFile VARCHAR(255) null,
ProductAvailability char(2) not null,
RightsCountry varchar(MAX) not null,
Deleted bit not null
)
insert into @ProductDetails(ProductDetailsID,ProductIdentifier,ProductID,
ProductFile,ProductAvailability,RightsCountry,Deleted) values
(123,567890,12,'filename.png',20,'AU CX CC CK HM NZ NU NF TK',0),
(124,567890,12,NULL,20,'AU CX CC CK HM NZ NU NF TK',0),
(125,567890,12,NULL,20,'AU CX CC CK HM NZ NU NF TK',0)
;With FillInFileNames as (
select *,
MAX(ProductFile) OVER (PARTITION BY ProductIdentifier,ProductID,
ProductAvailability,RightsCountry,Deleted)
as AnyFileName
from @ProductDetails
)
select * from FillInFileNames
where ProductFile is null and AnyFileName is not null
```
And the fact that aggregate functions will never return `NULL` if at least one input value wasn't `NULL`.
Result:
```
ProductDetailsID ProductIdentifier ProductID ProductFile ProductAvailability RightsCountry Deleted AnyFileName
---------------- -------------------- ----------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
124 567890 12 NULL 20 AU CX CC CK HM NZ NU NF TK 0 filename.png
125 567890 12 NULL 20 AU CX CC CK HM NZ NU NF TK 0 filename.png
```
---
It may also be instructive for the OP to observe that the top of my script isn't *much* more than the table information and sample data provided in their question - except mine is actually runnable.
It might be worth considering writing your samples in such a style in the future, because that way it can be immediately copy & pasted from your question into a query window. | ```
create view rows_to_delete
as
select *
from (
select *,
row_number() over(partition by ProductIdentifier order by ProductFile desc, ProductDetailsID) as rn
from t
) x
where rn > 1
and ProductFile is null
``` | T-SQL Select duplicate rows where at least 1 column has a value | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
This is a rather unique problem and I don;t know if there is an answer. Im trying to input a variable amount of records to insert into a table depending on the value of another table. This is what I have tried
```
insert into TABLE1
select TOP cast((select Value from TABLE3 WHERE column_name = 'blah') as int) * from TABLE2
```
So im trying to get the value from table 3, and use that value to grab the top x records from table 2 to be inserted into table 1.
the error listed is Incorrect syntax near cast. | OP doesn't specify the database they are using, but SQL Server allows a variable. try it out:
```
declare @YourTable table (RowID int identity(1,1), ColA char(4))
INSERT INTO @YourTable values ('a');INSERT INTO @YourTable values ('aa');INSERT INTO @YourTable values ('aaa');
INSERT INTO @YourTable values ('b');INSERT INTO @YourTable values ('bb');INSERT INTO @YourTable values ('bbb');
INSERT INTO @YourTable values ('c');INSERT INTO @YourTable values ('cc');INSERT INTO @YourTable values ('ccc');
declare @x int=5
select top (@x) * from @YourTable
```
output:
```
RowID ColA
----------- ----
1 a
2 aa
3 aaa
4 b
5 bb
(5 row(s) affected)
``` | ~~TOP x cannot be specified in a variable.~~It actually can, see KM's answer (which is definitely better than mine).
An option here would be a dynamic query
```
DECLARE @topx AS integer;
SET @topx = (select Value from TABLE3 WHERE column_name = 'blah')
DECLARE @query AS varchar(max);
SET @query = 'INSERT INTO table1 SELECT TOP ' + convert(varchar(10),@topx)
+ ' FROM table2'
exec sp_executesql query
``` | Select TOP x From table | [
"",
"sql",
"select",
""
] |
I need to remove duplicates from my table (user\_info). I always want to remove the row with the id column that is lower of the two rows being returned from my select/having query below. Any ideas on how to write the delete statement to remove the duplicates (lower user\_info.id column) from the results of my select/having query below? I'm using Oracle 11g.
**user\_info table structure:**
```
id (unique primary key number 10 generated by sequence)
user_id (number 10)
first_name (varchar2)
last_name (varchar2)
```
**data example:**
```
id user_id
______ ___________
37265 1455
265798 1455
```
**sql to show duplicates:**
```
select user_id, count(*)
from user_info
group by user_id
HAVING count(*) > 1
``` | Start with this to show you only the duplicates
```
Select user_id, count(*) NumRows, Min(Id) SmallestId, Max(Id) LargestId
From user_info
Group by user_id
HAVING count(*) > 1
```
This will show you the min and max for each `user_id` (with the same value for SmallestId and LargestId if there are no duplicates.
```
Select user_id, count(*) NumRows, Min(Id) SmallestId, Max(Id) LargestId
From user_info
Group by user_id
```
For a User, you want to keep the MaxId and Delete everything else. So you can write a DELETE statement to be
```
DELETE From user_info
Where Id Not IN
(
Select Max(Id)
From user_info
Group by user_id
)
```
This will get the | You can use the following query:
```
DELETE
FROM user_info
WHERE id NOT IN
(SELECT MAX(id)
FROM user_info
GROUP BY user_id);
```
This query will delete all the duplicate rows except the `user_id` row with maximum `id`.
Here's a **[SQL Fiddle](http://www.sqlfiddle.com/#!4/bbad4/1)** which demonstrates the delete. | Remove Duplicate Row Data | [
"",
"sql",
"oracle",
""
] |
This feels simple, but I can't find an answer anywhere.
I'm trying to run a query by time of day for each hour. So I'm doing a `Group By` on the hour part, but not all hours have data, so there are some gaps. I'd like to display every hour, regardless of whether or not there's data.
Here's a sample query:
```
SELECT DATEPART(HOUR, DATEADD(HH,-5, CreationDate)) As Hour,
COUNT(*) AS Count
FROM Comments
WHERE UserId = ##UserId##
GROUP BY DATEPART(HOUR, DATEADD(HH,-5, CreationDate))
```
My thought was to Join to a table that already had numbers 1 through 24 so that the incoming data would get put in it's place.
Can I do this with a CTE?
```
WITH Hours AS (
SELECT i As Hour --Not Sure on this
FROM [1,2,3...24]), --Not Sure on this
CommentTimes AS (
SELECT DATEPART(HOUR, DATEADD(HH,-5, CreationDate)) AS Hour,
COUNT(*) AS Count
FROM Comments
WHERE UserId = ##UserId##
GROUP BY DATEPART(HOUR, DATEADD(HH,-5, CreationDate))
)
SELECT h.Hour, c.Count
FROM Hours h
JOIN CommentTimes c ON h.Hour = c.Hour
```
###Here's a sample [Query From Stack Exchange Data Explorer](https://data.stackexchange.com/stackoverflow/revision/185460/239532/comments-by-hour) | You can use a recursive query to build up a table of whatever numbers you want. Here we stop at 24. Then left join that to your comments to ensure every hour is represented. You can turn these into times easily if you wanted. I also changed your use of `hour` as a column name as it is a keyword.
```
;with dayHours as (
select 1 as HourValue
union all select hourvalue + 1
from dayHours
where hourValue < 24
)
,
CommentTimes As (
SELECT DATEPART(HOUR, DATEADD(HH,-5, CreationDate)) As HourValue,
COUNT(*) AS Count
FROM Comments
WHERE UserId = ##UserId##
GROUP BY DATEPART(HOUR, DATEADD(HH,-5, CreationDate)))
SELECT h.Hour, c.Count
FROM dayHours h
left JOIN CommentTimes c ON h.HourValue = c.HourValue
``` | You can use a table value constructor:
```
with hours as (
SELECT hr
FROM (VALUES (1), (2), (3), (4), (5), (6), (7), (8), (9), (10), (11), (12)) AS b(hr)
)
etc..
```
You can also use a permanent auxilliary numbers table.
<http://dataeducation.com/you-require-a-numbers-table/> | Select Consecutive Numbers in SQL | [
"",
"sql",
"sql-server",
"common-table-expression",
"recursive-query",
""
] |
I am having some difficulties with probably a not so difficult SQL task..
I have two queries that I'd like to combine together. Both of them work fine separately, but when I try to combine them together I get different errors such as:
*Error 116: Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.*
At the same time I do not want to use **EXIST**, but **IN** instead.
Here are the queries:
First:
```
SELECT C.Id, C.Name, BC.Id AS BCID
FROM Customers AS C
RIGHT JOIN Bills AS Bc ON C.Id = BC.Bills_Customer
RIGHT JOIN Months AS M ON Bc.Month_Bills = M.Id
WHERE C.Argument = 'KP'
AND YEAR(bm.Datum) = YEAR(CURRENT_TIMESTAMP) AND MONTH(bm.Datum) = MONTH(CURRENT_TIMESTAMP)
ORDER BY C.Name
```
Second:
```
SELECT DISTINCT Account, LastLogin, Licences_Bills
FROM Licences
WHERE LastLogin > CONVERT(varchar,dateadd(d,-(day(dateadd(m,-1,getdate()-2))),dateadd(m,-1,getdate()-1)),106)
AND LastLogin < CONVERT(varchar,dateadd(d,-(day(getdate())),getdate()),106)
AND Access = 1 --AND Licences_Bills IN
ORDER BY Licences_Bills ASC
```
Results from the two queries look like that:
First:
```
+----------+---------+-----------+
| Id | Name | BCID |
+----------+---------+-----------+
| 1 | John | 500 |
+----------+---------+-----------+
| 2 | Max | 501 |
+----------+---------+-----------+
| 5 | Foo | 502 |
+----------+---------+-----------+
| 7 | Bar | 503 |
+----------+---------+-----------+
```
Second:
```
+----------+--------------+-------------------+
| Account | LastLogin | Licences_Bills |
+----------+--------------+-------------------+
| abc | 07.03.2014 | 500 |
+----------+--------------+-------------------+
| aac | 13.03.2014 | 500 |
+----------+--------------+-------------------+
| acb | 28.03.2014 | 504 |
+----------+--------------+-------------------+
| bca | 19.03.2014 | 506 |
+----------+--------------+-------------------+
```
Now I'd like to combine these two, so that it displays only rows where the **BCID** from the first query and the **Licences\_Bills** from the second query match.
I tried with **IN** and then a nested select, but did not work out. Any thoughts on what I am doing wrong? Clues and/or links to some valuable resources are also appreciated!
**EDIT:**
In the end, I'd like to have the second result list limited to those bills from the first query. This is why I was trying with IN and then nested select. INNER JOIN on the other hand would give me results as the intersection of both tables.
Also, I don't want to see the columns from the first query (as of what happens with join). Just the final result structured as the second query. | To get the second result list limited to bills you also find in the first query, you will have to Combine them either with IN or with EXISTS. I don't know why this didn't work for you. Maybe just a typo? The following should work. It simply combines the two statements with IN. So in the inner query I only select BC.ID and removed the order by clause.
```
SELECT DISTINCT Account, LastLogin, Licences_Bills
FROM Licences
WHERE LastLogin > CONVERT(varchar,dateadd(d,-(day(dateadd(m,-1,getdate()-2))),dateadd(m,-1,getdate()-1)),106)
AND LastLogin < CONVERT(varchar,dateadd(d,-(day(getdate())),getdate()),106)
AND Access = 1
AND Licences_Bills IN
(
SELECT BC.Id
FROM Customers AS C
RIGHT JOIN Bills AS Bc ON C.Id = BC.Bills_Customer
RIGHT JOIN Months AS M ON Bc.Month_Bills = M.Id
WHERE C.Argument = 'KP'
AND YEAR(bm.Datum) = YEAR(CURRENT_TIMESTAMP) AND MONTH(bm.Datum) = MONTH(CURRENT_TIMESTAMP)
)
ORDER BY Licences_Bills ASC
``` | ```
SELECT * FROM
(
SELECT C.Id, C.Name, BC.Id AS BCID
FROM Customers AS C
RIGHT JOIN Bills AS Bc ON C.Id = BC.Bills_Customer
RIGHT JOIN Months AS M ON Bc.Month_Bills = M.Id
WHERE C.Argument = 'KP'
AND YEAR(bm.Datum) = YEAR(CURRENT_TIMESTAMP) AND MONTH(bm.Datum) = MONTH(CURRENT_TIMESTAMP)
) as T1
INNER JOIN
(
SELECT DISTINCT Account, LastLogin, Licences_Bills
FROM Licences
WHERE LastLogin > CONVERT(varchar,dateadd(d,-(day(dateadd(m,-1,getdate()-2))),dateadd(m,-1,getdate()-1)),106)
AND LastLogin < CONVERT(varchar,dateadd(d,-(day(getdate())),getdate()),106)
AND Access = 1
) T2
ON T1.BCID=T2.Licences_Bills
``` | Combine two separate SQL queries into one | [
"",
"mysql",
"sql",
""
] |
I have a table for a issue tracking web app that maps issues to ticket numbers. A given issue can have (hypothetically) an infinite amount of tickets mapped to it. I want to do a SQL Query that will get an issue that might possibly have multiple tickets attached to it.
For example:
```
issue_id | ticket_id
--------------------
1 | 100
1 | 101
2 | 101
```
(SQL Fiddle: <http://sqlfiddle.com/#!2/b3c34/3>)
(A little background) I'm working on a new search page for this web app, and one of the search-able fields is ticket number. The user has the ability to specify any number of ticket numbers to search for.
So let's say a user is trying to find all issues numbers that have ticket numbers 100 and 101 mapped to them. The following SQL query returns no rows:
```
select issue_id
from tickets
where ticket_id = 100 and ticket_id = 101;
```
Can someone point me in the right direction? Is there a way to do the above efficiently with one query? Note that there could possibly be hundreds of issue numbers returned in the query (the ticket numbers are just one small piece of a much larger query) so I want this to be as simple as possible.
Thanks. | Your `tickets` table should presumably be a [Junction Table](http://en.wikipedia.org/wiki/Junction_table). However...
```
select distinct issue_id
from tickets t
where exists (select 1 from tickets where ticket_id = 100 and issue_id = t.issue_id)
and exists (select 1 from tickets where ticket_id = 101 and issue_id = t.issue_id);
```
Or:
```
select distinct issue_id
from tickets
where issue_id in (select issue_id from tickets where ticket_id = 100)
and issue_id in (select issue_id from tickets where ticket_id = 101);
```
Will do what you're asking for. The latter is often easier to understand, but the former will often perform better.
You could also do this, but it's a set operation query and is often discouraged. However, the Execution plan on SQLFiddle indicates this is the best of the three.
```
select issue_id from tickets where ticket_id = 100
intersect
select issue_id from tickets where ticket_id = 101;
```
There's at least one other way to do it, too, with a self `INNER JOIN`. | ```
select issue_id
from tickets
where ticket_id in (101,102)
group by issue_id
having count(distinct ticket_id) = 2
``` | Query for Many-To-One With AND | [
"",
"sql",
"sql-server",
""
] |
I'm having trouble with a SQL query. My schema describes a many to many relationship between articles in the `articles` table and categories in the `categories` table - with the intermediate table `article_category` which has an `id`, `article_id` and `category_id` field.
I want to select all articles which only have the categories with id `1` and `2`. Unfortunately this query will also select any articles which have those categories in addition to any others.
For example, this is a sample output from the SQL (**with categories shown for descriptive purposes**). You can see that while the query selected the article with id of `10`, it also selected the article with an id of `11` despite having one extra category.
```
+-------+------------+
| id | categories |
+-------+------------+
| 10 | 1,2 |
| 11 | 1,2,3 |
+-------+------------+
```
This is the output that I want to achieve from selecting articles with only categories `1`and `2`.
```
+-------+------------+
| id | categories |
+-------+------------+
| 10 | 1,2 |
+-------+------------+
```
Likewise, this is the output what I want to achieve from selecting articles with only categories `1`, `2` and `3`.
```
+-------+------------+
| id | categories |
+-------+------------+
| 11 | 1,2,3 |
+-------+------------+
```
This is the SQL I have written. What am I missing to achieve the above?
```
SELECT articles.id
FROM articles
WHERE EXISTS (
SELECT 1
FROM article_category
WHERE articles.id = article_id AND category_id IN (1,2)
GROUP BY article_id
)
```
Many thanks! | Assuming you want more than just the article's id:
```
SELECT a.id
,a.other_stuff
FROM articles a
JOIN article_category ac
ON ac.article_id = a.id
GROUP BY a.id
HAVING GROUP_CONCAT(DISTINCT ac.category_id ORDER BY ac.category_id SEPARATOR ',') = '1,2'
```
If all you want is the article's id then try this:
```
SELECT article_id
FROM article_category
GROUP BY article_id
HAVING GROUP_CONCAT(DISTINCT category_id ORDER BY category_id SEPARATOR ',') = '1,2'
```
See it in action at <http://sqlfiddle.com/#!2/9d213/4>
Should also add that the advantage of this approach is that it can support the checking of any number of categories without having to change the query. Just make '1,2' a string variable and change what gets passed into the query. So, you could just as easily search for articles with categories 1, 2, and 7 by passing a string of '1,2,7'. No additional joins are needed. | You can left join `category_id` on `category.id` and then [GROUP\_CONCAT](http://mahmudahsan.wordpress.com/2008/08/27/mysql-the-group_concat-function/) to get all categories, like you wrote in explanation (1st table) and than using `HAVING` match with any set you like ( '1,2' from example)
also with that approach you can easily make this query dynamic with php or any other language
```
SELECT articles.id
FROM articles
WHERE EXISTS (
SELECT GROUP_CONCAT(c.id) AS grp
FROM article_category
LEFT OUTER JOIN categories AS c ON c.id = article_category.category_id
WHERE articles.id = article_id
GROUP BY article_id
HAVING grp = '1,2'
)
``` | MySQL Select Where In Many to Many | [
"",
"mysql",
"sql",
"many-to-many",
""
] |
These are my tables:
**Table\_Bill\_Summary**
`| Date | PersonId | BillNo |`
**Table\_Bill\_Items**
`| BillNo | ItemId | Quantity |`
**Item\_MasterTable**
`| ItemId | ItemName | ItemRate |`
I am going to specify a PersonId. This is what I want to print:
```
SELECT *
FROM Table_Bill_Summary
WHERE PersonId=@X
(SELECT IM.ItemName,BI.Quantity,IM.ItemRate
FROM Table_Bill_Items AS BI
INNER JOIN Item_MasterTable AS IM ON BI.ItemId=IM.ItemId
WHERE BI.BillNo=??)
```
My result should look like:
```
23/04/2013 Person123 Bill32
Item20 23 100
Item21 20 200
Item23 1 300
23/04/2013 Person123 Bill39
Item2 2 100
Item11 40 800
Item43 1 700
```
I want a child `Select` Query to be run for each row retrieved by the parent `Select` query on the column `BillNo` | ```
select FLD1,FLD2,FLD3 from
(
SELECT CAST(Date as varchar(10)) as FLD1 ,CAST(PersonId as varchar(10)) as FLD2,
cast(BillNo as varchar(10)) as FLD3,1 as FLD4, Billno as fld5
FROM Table_Bill_Summary WHERE PersonId =@X
union
SELECT CAST(IM.ItemName as varchar(10)) as FLD1 ,CAST(BI.Quantity as varchar(10)) as FLD2,CAST(IM.ItemRate as varchar(10)) as FLD3 ,2 as FLD4, BS.Billno as fld5
FROM Table_Bill_Summary BS inner join Table_Bill_Items AS BI on bs.BillNo=BI.BillNo
INNER JOIN Item_MasterTable AS IM ON BI.ItemId=IM.ItemId
WHERE Bs.PersonId =@X
) as x order by fld5,fld4
``` | You can't do this in SQL. Instead, perform the operation in your application by fetching the joined results (bills and items) sorted by bill and keeping track of the last seen bill when iterating through the resultset:
```
string stm = @"
SELECT BillNo, Date, ItemName, Quantity, ItemRate
FROM Table_Bill_Summary
JOIN Table_Bill_Items USING (BillNo)
JOIN Item_MasterTable USING (ItemId)
WHERE PersonId = @Person
ORDER BY BillNo
";
MySqlCommand cmd = new MySqlCommand(stm, conn);
cmd.Prepare();
cmd.Parameters.AddWithValue("@Person", person_id);
MySQLDataReader rdr = cmd.ExecuteReader();
bool isMore = rdr.Read();
while (isMore) {
int current_bill = rdr.GetInt32(0);
// output bill
do {
// output item
} while (isMore = rdr.Read() && rdr.GetInt32(0) == current_bill);
}
``` | Parent Select SQL Query generating Child Select | [
"",
"mysql",
"sql",
"sql-server",
"select",
""
] |
I am new to Regular Expressions and any help is highly appreciated.
* Pattern like W00000,W00001,W00002,W00004
* Must begin with W
* Each string before comma must be six characters
* String can only be repeated four times
* Comma in between
* Must not begin or end with comma
I tried below pattern and some others, like `(^[W]{1}\d{5}){1,4}')`, and none of them work correctly:
```
Select 'X' from dual Where REGEXP_LIKE ('W12342','(^[W]{1}\d{5})(?<!,)$')
``` | My understanding is that the OP is saying the match should *fail* if the string begins or ends with a comma, not just that the preceding or trailing commas shouldn't match, so anchors are needed. Also, based on the regex he attempted, I infer that a single group, such as `W00000`, should match. So, I think the regex should be this, if the characters following the **W** must always be digits:
```
^W[:digit:]{5}(,W[:digit:]{5}){0,3}$
```
Or this, if they can be something other than digits:
```
^W[^,]{5}(,W[^,]{5}){0,3}$
```
---
**UPDATE:**
The OP posted the following comment:
> I am on Oracle 11g and [:digit:] doesn't work. When I replace it with [0-9] it then works fine.
According to [the documentation](http://docs.oracle.com/cd/E11882_01/appdev.112/e41502/adfns_regexp.htm#ADFNS1012), Oracle 11g conforms to the POSIX regex standard and *should* be able to use POSIX character classes such as **[:digit:]**. However, I noticed in the docs that Oracle 11g does support Perl-style backslash character class abbreviations, which I didn't think was the case when I originally wrote this answer. In that case, the following should work:
```
^W\d{5}(,W\d{5}){0,3}$
``` | Well in that case, you can do this:
```
(W[^,]{5},){3}W[^,]{5}
``` | Write regex for pattern like W00001 | [
"",
"sql",
"regex",
"oracle",
""
] |
I need exclude text from the **"<==#"** to the end (like %)
```
"TestDescription <==# info "dynamic text" ==>"
```
I tried use Replace with % but it does not work
```
select replace ( testfield, '<==# %', '') from table
``` | The following will do what you want:
```
select left(testfield, charindex('<==#', testfield) - 1)
```
There is no reason to use wildcards for this. You only want the left part of the string before that substring. | If you want to replace `<==#` to `%`, then use
```
replace(testfield,'<==#','%') as ColName
``` | How to use Replace with % | [
"",
"sql",
"sql-server-2008",
""
] |
I am trying to complete an sql query to show how many GCSEs a student has on record.]
```
*STUDENT *SUBJECT *SCHOOL
ABB13778 | English | Social Care & Early Years
ABB13778 | Information and Communication Technology | Social Care & Early Years
ABB13778 | Mathematics | Social Care & Early Years
ABB13778 | Media Studies | Social Care & Early Years
```
For example this student should recieve a count of 4 as there is 4 distinct subjects assigned to the school and student ID.
I can count the items but the output should be by school and number(see below), and I am not sure how toy form a case to create this
```
NUM OF STUDENT with each amount of GCSE
SCHOOL 1 2 3 4 5 6 7 8 9 10 11
Social Care & Early Years | 5 1 2 7 0 1 13 15 8 4 2
Built Environment |
Business & Computing |
```
This is probably simpler than I am thinking but at the minute I cant get my head around it. Any help would be greatly appreciated. | After grouping the data by school and student, you need to then run it through a `PIVOT` on the count of Students with each number of subjects, to get the histogram 'bins':
```
SELECT [School], [0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11]
FROM
(
SELECT School, Student, COUNT([Subject]) AS Subjects
FROM Student_GCSE
GROUP BY School, Student
) x
PIVOT
(
COUNT(Student)
FOR Subjects IN ([0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11])
) y;
```
[SqlFiddle here](http://sqlfiddle.com/#!3/b4660/1)
I've assumed a finite number of subjects, but you can derive the columns as well using [dynamic sql](https://stackoverflow.com/a/14902703/314291) | `Group by` should solve this, Something like following:
```
select SCHOOL, subject, count(*) as NUM_STUDENTS from records
group by STUDENT, SCHOOL;
``` | SQL Count. How can I count how many distinct values are in a table when an other two columns are matching? | [
"",
"sql",
"sql-server",
"count",
"distinct",
"multiple-columns",
""
] |
I am facing a problem with `SUM` statement.
This query returns `MY_ID = 1` and `QTY = 7`
```
select my_id, sum(qty) qty
from
(
select 1 my_id ,2 qty from dual
union
select 1 my_id, 5 qty from dual
)
group by my_id;
```
But this one returns `MY_ID = 1` and `QTY = 5` instead of `QTY = 10`.
```
select my_id, sum(qty) qty
from
(
select 1 my_id ,5 qty from dual
union
select 1 my_id, 5 qty from dual
)
group by my_id;
```
How can I summary the two quantity in case of the two values **are the same**? | Use union all:
```
select my_id, sum(qty) qty
from
(
select 1 my_id ,5 qty from dual
union all
select 1 my_id, 5 qty from dual
)
group by my_id;
``` | Try using union all:
The below works:
```
select my_id, sum(qty) qty
from
(
select 1 my_id ,5 qty from dual
union all
select 1 my_id, 5 qty from dual
)
group by my_id;
```
this is because 5 union 5 is always 5. if you do union all it includes everything irrespective of it being the same! | Oracle SUM returns false summary with identicals values returing from an SELECT UNION | [
"",
"sql",
"database",
"oracle",
"sum",
""
] |
I have the following "Unit" table
```
Description
-------------
PERCENTAGE
KG * KILOMETRE
KG * METRE
KG * MILE
KG * YARD
POUND * KILOMETRE
POUND * METRE
POUND * MILE
POUND * YARD
TON * KILOMETRE
TON * METRE
TON * MILE
TON * YARD
TONNE * KILOMETRE
TONNE * METRE
TONNE * MILE
TONNE * YARD
COUNT * KILOMETRE
COUNT * METRE
COUNT * MILE
COUNT * YARD
```
I have to transform each unit of form `A * B` to `A/B` and `PERCENTAGE` to `%` in the DB.
I wrote the following code using Cursors
**QUERY:**
```
DECLARE @textToDisplay varchar(50);
DECLARE CurrencyCursor Cursor Local
For SELECT Description FROM Unit;
OPEN CurrencyCursor
FETCH NEXT FROM CurrencyCursor into @textToDisplay;
WHILE @@FETCH_STATUS = 0
Begin
@textToDisplay =
CASE @textToDisplay --line 1
WHEN 'PERCENTAGE' THEN '%'
WHEN '% * %' THEN REPLACE(@textToDisplay ,' * ', '/') --line 2
ELSE @textToDisplay
END
Print @textToDisplay
FETCH NEXT FROM CurrencyCursor into @textToDisplay;
End
CLOSE CurrencyCursor --line 3
```
I get the following errors:
```
`line 1` - Incorrect syntax near '@textToDisplay'
`line 2` - Incorrect syntax near '@textToDisplay'. Expecting '(', or SELECT
`line 3` - Incorrect syntax near 'CLOSE'. Expecting CONVERSATION
```
Cannot quite understand the cause of the errors. | ```
DECLARE @textToDisplay varchar(50)
DECLARE CurrencyCursor CURSOR FOR
SELECT Patientid FROM Patient;
OPEN CurrencyCursor
FETCH NEXT FROM CurrencyCursor into @textToDisplay;
WHILE @@FETCH_STATUS = 0
Begin
SET @textToDisplay =
CASE @textToDisplay --line 1
WHEN 'PERCENTAGE' THEN '%'
WHEN '% * %' THEN REPLACE(@textToDisplay ,' * ', '/') --line 2
ELSE @textToDisplay
END
Print @textToDisplay
FETCH NEXT FROM CurrencyCursor into @textToDisplay;
End
CLOSE CurrencyCursor
``` | Why not simply use nested replace?
```
SELECT REPLACE(REPLACE(Description, '*', '/'), 'PERCENTAGE', '%')
``` | Cursors in SQL Server not functioning | [
"",
"sql",
"sql-server",
"cursor",
""
] |
I'm pretty stuck at the moment due to by lack of SQL knowledge!
I have two tables with the following criteria:
```
Table1
UPC
Country
Table2
UPC
Country
```
I need to see all of the rows in Table 1 with the corresponding UPC from Table two and where a country is missing from table 2.
So for example:
```
UPC1 |Country1 |UPC2 |Country2
12345 |UK |12345 |UK
12345 |IE |12345 |IE
12345 |DE |NULL |NULL
12345 |FR |12345 |FR
```
I've tried the following code:
```
select *
from CPRSLRScheduled cprs join R2LRDig r2
on cprs.UPC = r2.upc
where cprs.country_iso_code not in (r2.country_id)
```
I know this is a real beginners' question but I really need a helping hand! | Use an outer join. The following statement gives you all records of table 1 and the matches of table 2. If no match is found, you get NULL values:
```
select *
from CPRSLRScheduled cprs
left outer join R2LRDig r2 on cprs.UPC = r2.upc and cprs.country_iso_code = r2.country_id
``` | ```
select t1.upc,t1.country,t2.upc,t2.country
from table1 t1 inner join table2 t2
on t1.upc=t2.upc where t2.country IS NULL
``` | Joining two tables and need to return results which have same ID but different criteria | [
"",
"sql",
""
] |
I'm trying to list all the Products that have had no sales. I'm really close but I'm trying to use the NOT EXISTS statement to display all the ProductID's that are in the Product table, but not in the Orderline table; and hence have no sales. My code is as follows;
```
SELECT product.productid
FROM product
JOIN orderline ON product.productid = orderline.productid
WHERE NOT EXISTS (
SELECT orderline.productid
FROM orderline
)
ORDER BY productid
``` | You can avoid the Subselect by simply doing a `LEFT JOIN`:
```
SELECT product.productid
FROM product
LEFT JOIN orderline USING (productid)
WHERE orderline.productid IS NULL
ORDER BY product.productid
```
`LEFT JOIN` will list *all* rows in `product` even when there is no JOIN partner in `orderline`. In that case all columns in `orderline` have `NULL` values. These are the rows you want in the result. | If you must use `not exists`, try this:
```
SELECT *
FROM product p
WHERE NOT EXISTS (
SELECT 1
FROM orderline o
WHERE p.productid = o.productid
)
ORDER BY p.productid
``` | SQL - Products with No Sales | [
"",
"mysql",
"sql",
""
] |
I have this table
```
f_id | user_id | sent
==============================
1 | 1 | 0
1 | 2 | 1397820533
1 | 3 | 0
1 | 4 | 1397820533
2 | 1 | 1397820533
2 | 2 | 1397820533
2 | 3 | 1397820533
3 | 1 | 1397820533
3 | 2 | 1397820533
```
now I would like to have all `f_id`'s where **all** `sent` fields have a timestamp ( != 0 )
```
SELECT * FROM table WHERE sent != 0 GROUP BY f_id
```
returns all three cause there are some which have a timestamp.
A a result I expect
```
f_id
=====
2
3
```
cause `f_id` still have some 0 values | You are close, but you want to move the condition to the `having` clause:
```
SELECT f_id
FROM table
GROUP BY f_id
HAVING SUM(sent = 0) = 0;
```
The `having` clause counts the number of rows with `sent = 0`. The `= 0` means there are none of them. | ```
SELECT Distinct f_id
FROM table
WHERE sent >= 0
``` | Get ids where all values of a field have a certain value | [
"",
"mysql",
"sql",
""
] |
I have a FK inside my table but i want to modify the parent table for the FK . so is there an alter command that can achieve this ? or i need to remove the FK and create a new one ?
Thanks | Add this to your PK and it will automatically update all FKs for you:
```
ON UPDATE CASCADE
```
For full details, you can read [this article](http://technet.microsoft.com/en-us/library/aa933119%28v=sql.80%29.aspx).
**EDIT** Based on your comment, if you want to change the PK data type, it depends on the change:
* If the old type can be implicitly casted to the new type without any loss:
1. Change the PK type first.
2. Change the FK type to the same.
* If the old type cannot be implicitly casted to the new type without any loss:
1. Break the relationship first (i.e. remove the FK restriction/index).
2. Convert the PK. If the data needs to be modified, save both the old values and the new ones in a temporary table.
3. Convert the FK. If the PK data was changed in previous step, update the FK using the mapped values from the temporary table.
4. Create the relationship again (i.e. create the FK restriction/index).
To modify the data type, use the `ALTER` command, the syntax is:
```
ALTER TABLE table_name
ALTER COLUMN column_name datatype
```
Examples:
```
ALTER TABLE table_name
ALTER COLUMN id NUMBER(10,2);
ALTER TABLE table_name
ALTER COLUMN id VARCHAR(20);
```
For full details, you can read [this article](http://www.w3schools.com/sql/sql_alter.asp). | Looks like you are looking for `alter` statement but since you didn't mention exactly what you are looking to modify; I assume that you want to change column data type size. You can do something like this (an example; say you want to change size from 10 to 15)
```
alter table sample3
alter column name varchar(15)
```
**EDIT:**
In that case this is what you should be doing. You need to drop the existing constraint and recreate the constraint to point to `TableC`
```
alter table TableA
drop constraint your_FK_constraint_name
alter table TableA
add constraint constraint_name
FOREIGN KEY (column_name) references TableC(some other column name)
```
An Example:
```
alter table sample2
drop constraint FK__sample2__realnam__09DE7BCC
alter table sample2
add constraint FK__sample2__realnam
FOREIGN KEY (realname) references sample1(name)
``` | How i can modify the Parent table for my Sql server 2008 r2 FK | [
"",
"sql",
"sql-server-2008-r2",
""
] |
I have a user table (id,group) and need to select 1 if a user is not a member of a group. A Member can be a member of multiple groups so there may be more than one record for each ID(not unique)
I can only return one(pass/fail) value and I need to basically check all of the records to see if the user is a member of 'admin'. If the are a member of 'admin' i need the statement to fail. If none of the user's groups is admin then I need it to pass. I have tried a couple of different ways but I dont know if I am on the correct path.
```
SELECT 1
FROM GRP
WHERE USER = 'name'
AND GROUP NOT IN ('ADMIN')
SELECT 0
FROM GRP
WHERE USER = 'name'
AND EXISTS
(
SELECT 1 FROM GRP
WHERE USER = 'name'
AND GROUP NOT IN ('ADMIN')
)
```
EDIT = How I solved my problem
```
SELECT 1
FROM GRP
WHERE 'name' NOT IN
(
select USER
from GRP
group by USER
having sum(case when GROUP = 'ADMIN' then 1 else 0 end) = 1
)
``` | You can use `group by` and then check whether the admin group is in the list in the `having` clause:
```
select user
from grp
group by user
having sum(case when group = 'ADMIN' then 1 else 0 end) = 0;
```
The above returns all users. You can add the `where` clause for a particular user if you like.
If you want a flag for the user, instead of filtering out the ones in the admin group:
```
select user, max(case when group = 'ADMIN' then 1 else 0 end) as AdminFlag
from grp
group by user;
```
EDIT:
If you want a 0 or 1 flag for a given user:
```
select max(case when group = 'ADMIN' then 1 else 0 end) as IsInAdminFlag
from grp
where user = 'name';
``` | ```
SELECT 1 AS COL
FROM GRP
WHERE USER = 'name'
AND GROUP NOT IN ('ADMIN')
UNION ALL
SELECT 0 AS COL
FROM GRP
WHERE USER = 'name'
AND EXISTS
(
SELECT 1 FROM GRP
WHERE USER = 'name'
AND GROUP NOT IN ('ADMIN')
)
``` | Selecting only one result from a set | [
"",
"sql",
"select",
""
] |
I'm trying to update a field based on a field of another table. Here is the code:
```
UPDATE h
SET h.strength = c.strength
FROM hesters AS h
INNER JOIN campers AS c
ON h.camper_id = c.id
```
Getting "#1064 - You have an error in your SQL syntax;"
I'm basing my code off this answer [here](https://stackoverflow.com/questions/9588423/sql-server-inner-join-when-updating).
Anyone spot the syntax error? | I don't know why the code from the previous linked answer didn't work, but here is what I ended up going with, from the mysql documentation on [UPDATE](http://dev.mysql.com/doc/refman/5.0/en/update.html) (search for "join").
```
UPDATE hesters AS h,campers AS c
SET h.strength = c.strength
WHERE h.camper_id = c.id
``` | Try doing something like:
```
UPDATE hesters AS h
INNER JOIN campers AS c
ON h.camper_id = c.id
SET h.strength = c.strength
```
---
***update***
This works on [sqlfiddle](http://www.sqlfiddle.com/#!2/ff5ed3/1). | mysql update column inner join another table | [
"",
"mysql",
"sql",
""
] |
I receive reports in which the data is `ETL` to the DB automatically. I extract and transform some of that data to load it somewhere else. One thing I need to do is a `DATEDIFF` but the year needs to be exact (i.e., 4.6 years instead of rounding up to five years.
The following is my script:
```
select *, DATEDIFF (yy, Begin_date, GETDATE()) AS 'Age in Years'
from Report_Stage;
```
The `'Age_In_Years'` column is being rounded. How do I get the exact date in years? | Have you tried getting the difference in months instead and then calculating the years that way? For example 30 months / 12 would be 2.5 years.
Edit: This SQL query contains several approaches to calculate the date difference:
```
SELECT CONVERT(date, GetDate() - 912) AS calcDate
,DATEDIFF(DAY, GetDate() - 912, GetDate()) diffDays
,DATEDIFF(DAY, GetDate() - 912, GetDate()) / 365.0 diffDaysCalc
,DATEDIFF(MONTH, GetDate() - 912, GetDate()) diffMonths
,DATEDIFF(MONTH, GetDate() - 912, GetDate()) / 12.0 diffMonthsCalc
,DATEDIFF(YEAR, GetDate() - 912, GetDate()) diffYears
``` | All `datediff()` does is compute the number of period boundaries crossed between two dates. For instance
```
datediff(yy,'31 Dec 2013','1 Jan 2014')
```
returns 1.
You'll get a more accurate result if you compute the difference between the two dates in days and divide by the mean length of a calendar year in days over a 400 year span (365.2425):
```
datediff(day,{start-date},{end-date},) / 365.2425
```
For instance,
```
select datediff(day,'1 Jan 2000' ,'18 April 2014') / 365.2425
```
return `14.29461248` — just round it to the desired precision. | Calculate exact date difference in years using SQL | [
"",
"sql",
"sql-server",
"datediff",
""
] |
I created an Access front end for a SQL DB on my PC for use throughout my company. I am using a file ODBC connection and putting both the ODBC file and the Access file on a shared network drive.
When I load the access file, for some reason it seems to default to using my windows login credentials and pulls in the data perfectly. When a user attempts to open the file, they receive an error message saying "ODBC --call failed.". I can open the Linked Table Manager for them and check 'ask for new location' then specify the ODBC file and it all works fine...however it doesn't seem to save anything. I get the error each time someone other then myself opens this file.
Any idea what could be wrong? I am not an Access guy by trade, it just seems to be the tool we need for the moment.
--EDIT: For Clarification I am using a file ODBC connection
--Edit 2--
Riddle me this. So I have been troubleshooting this issue and I came across something interesting. I was logged in as one of my users and did the following:
1. Create a new access file that references a file ODBC connection on the desktop.
2. Create 3-4 linked tables in the access file, using the ODBC file on the desktop.
3. Save and close the access file.
4. Re-Open said file.... and I get an ODBC connection error! Right after everything was fine in a fresh file!
Anyone ever experience this? | Well, I was able to narrow the issue a bit. Access for some reason keeps trying to use Windows Credentials instead of the username in my ODBC file. I can't find a way around it, but I was able to resolve the issue by creating logins on my SQL Server for the windows users that need access.
I am not incredibly happy about needing to manage more logins, but that's what i did to resolve this issue. | i assume you didn't install the ODBC correctly on each users PC.
you should create the ODBC-definition. You can create the relevant statements directly in the registry, see this branch
HKEY\_LOCAL\_MACHINE\SOFTWARE\ODBC\ODBC.INI
if you give the same name as on your developer machine, then it works. that's how i do it with my client applications that i develop on my machine and then install it at client site | Access ODBC Issue: ODBC--Call failed | [
"",
"sql",
"ms-access",
"odbc",
"ms-office",
""
] |
I'm trying to determine whether a product exists in the product table already. When I run this bit of tsql, it should return 1 and exit out of the proc, because the product id 7777 does not exist in the product table, but it's returning 0. If I run it without the if statement and just execute the select statement, it says that the `@prodID` is `null`. I'm wondering why is it not going into the if statement seeing as I am checking if it's a null value. Thanks in advance for any help.
```
Declare @ProdID int
select @ProdID = dbo.productTbl.ProductID
from dbo.ProductTbl
inner join dbo.OrderTbl
on dbo.ProductTbl.ProductID = dbo.OrderTbl.ProductID
where dbo.OrderTbl.ProductID = 7777
if(@ProdID = null)
begin
raiserror('The product does not exist',16,1)
return 1
end
return 0
``` | In SQL Server, use `IS NULL` to check for a null value rather than `= null`.
```
if(@ProdID IS NULL)
begin
raiserror('The product does not exist',16,1)
return 1
end
return 0
``` | Use IS NULL operator.
Also, there is no reason to write code after RAISERROR, it is not executed.
```
IF @ProdID IS NULL
RAISERROR('The product does not exist',16,1)
``` | Checking if a column has a null value tsql | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I was using a query in which it has both "and" and "or" logic.Here is my query,
```
select *
from products_event
where products_event.active > 0
and is_event_activated > 0
and is_user_activated > 0
and quantity > 0
and products_event.name like '%" . $search_keyword . "%'
or products_event.short_desc like '%" . $search_keyword . "%'
```
I am getting a result but it also list the products which are having '0' as value for active column and so on.
The php my admin also not showing any error in the query.
Thank you | You need to add brackets. Try this:
```
select *
from products_event
where products_event.active > 0
and is_event_activated > 0
and is_user_activated > 0
and quantity > 0
and
(products_event.name like '%" . $search_keyword . "%'
or products_event.short_desc like '%" . $search_keyword . "%')
``` | You need to respect the precedence of logical operators. `and` has precedence over `or`, as in multiplication has precedence over addition in math. Brackets make sure that your `or` condition is satisfied first.
Your first query is also syntatically correct, so it is only natural that you don't see any errors.
```
select *
from products_event
where products_event.active > 0
and is_event_activated > 0
and is_user_activated > 0
and quantity > 0
and
(products_event.name like '%" . $search_keyword . "%'
or products_event.short_desc like '%" . $search_keyword . "%')
``` | Did "AND" and "OR" will work in same query? | [
"",
"mysql",
"sql",
""
] |
I have the following table `test`
```
Id Code ParentId
1 R O
2 Y O
3 P O
4 O NULL
```
I need to update `test` like that :
```
Id Code ParentId
1 R 4
2 Y 4
3 P 4
4 O NULL
```
I tried that but it doesn't work , any idea ?
```
update [dbo].[test]
set [ParentId] =
CASE WHEN [ParentId]='' THEN [Id]
else select top 1 [Id] from [dbo].[PNL] where ParentId=[Code]
End
```
I got the table `test updated`
```
Id Code ParentId
1 R NULL
2 Y NULL
3 P NULL
4 O NULL
``` | With updates and deletes it is usually safer to first test the select:
```
select t1.*,
case when t1.parentid is null then t1.id
else (select top 1 t2.Id from #t t2 where t1.ParentId = t2.Code) end as new_parentid
from #t t1
```
and then do the actual update using CTE:
```
with x as (
select t1.*,
case when t1.parentid is null then t1.id
else (select top 1 t2.Id from #t t2 where t1.ParentId = t2.Code) end as new_parentid
from #t t1
)
update x
set parentid = new_parentid
``` | A direct fix is:
- Put the sub-query in `()`
- Make sure to specify `[test]` in that sub-query
*(I've had to guess whether `ParentID` or `[code]` come from `[test]`.)*
```
update [dbo].[test]
set [ParentId] =
CASE WHEN [ParentId]='' THEN [Id]
else (select top 1 [Id] from [dbo].[PNL] where ParentId=[test].[Code])
End
``` | Update table using case when | [
"",
"sql",
"sql-server",
""
] |
I have a table of users eg:
```
create table "user" (
id serial primary key,
name text not null,
superuser boolean not null default false
);
```
and a table with jobs:
```
create table job (
id serial primary key,
description text
);
```
the jobs can be assigned to users, but only for superusers. other users cannot have jobs assigned.
So I have a table whereby I see which job was assigned to which user:
```
create table user_has_job (
user_id integer references "user"(id),
job_id integer references job(id),
constraint user_has_job_pk PRIMARY KEY (user_id, job_id)
);
```
But I want to create a check constraint that the `user_id` references a user that has `user.superuser = True`.
Is that possible? Or is there another solution? | This would work for INSERTS:
```
create or replace function is_superuser(int) returns boolean as $$
select superuser from "user" where id = $1;
$$ language sql;
```
And then a check constraint on the user\_has\_job table:
```
create table user_has_job (
user_id integer references "user"(id),
job_id integer references job(id),
constraint user_has_job_pk PRIMARY KEY (user_id, job_id),
constraint chk_is_superuser check (is_superuser(user_id))
);
```
Works for inserts:
```
postgres=# insert into "user" (name,superuser) values ('name1',false);
INSERT 0 1
postgres=# insert into "user" (name,superuser) values ('name2',true);
INSERT 0 1
postgres=# insert into job (description) values ('test');
INSERT 0 1
postgres=# insert into user_has_job (user_id,job_id) values (1,1);
ERROR: new row for relation "user_has_job" violates check constraint "chk_is_superuser"
DETAIL: Failing row contains (1, 1).
postgres=# insert into user_has_job (user_id,job_id) values (2,1);
INSERT 0 1
```
However this is possible:
```
postgres=# update "user" set superuser=false;
UPDATE 2
```
So if you allow updating users you need to create an update trigger on the users table to prevent that if the user has jobs. | The only way I can think of is to add a unique constraint on `(id, superuser)` to the `users` table and reference that from the `user_has_job` table by "duplicating" the `superuser` flag there:
```
create table users (
id serial primary key,
name text not null,
superuser boolean not null default false
);
-- as id is already unique there is no harm adding this additional
-- unique constraint (from a business perspective)
alter table users add constraint uc_users unique (id, superuser);
create table job (
id serial primary key,
description text
);
create table user_has_job (
user_id integer references users (id),
-- we need a column in order to be able to reference the unique constraint in users
-- the check constraint ensures we only reference superuser
superuser boolean not null default true check (superuser),
job_id integer references job(id),
constraint user_has_job_pk PRIMARY KEY (user_id, job_id),
foreign key (user_id, superuser) references users (id, superuser)
);
insert into users
(id, name, superuser)
values
(1, 'arthur', false),
(2, 'ford', true);
insert into job
(id, description)
values
(1, 'foo'),
(2, 'bar');
```
Due to the `default` value, you don't have to specify the `superuser` column when inserting into the `user_has_job` table. So the following insert works:
```
insert into user_has_job
(user_id, job_id)
values
(2, 1);
```
But trying to insert arthur into the table fails:
```
insert into user_has_job
(user_id, job_id)
values
(1, 1);
```
This also prevents turning ford into a non-superuser. The following update:
```
update users
set superuser = false
where id = 2;
```
fails with the error
> ERROR: update or delete on table "users" violates foreign key constraint "user\_has\_job\_user\_id\_fkey1" on table "user\_has\_job"
> Detail: Key (id, superuser)=(2, t) is still referenced from table "user\_has\_job". | PostgreSQL check constraint for foreign key condition | [
"",
"sql",
"postgresql",
"foreign-keys",
"check-constraints",
""
] |
I have a simple data set in SQL Server that appears like this
```
**ROW Start End**
0 1 2
1 3 5
2 4 6
3 8 9
```
Graphically, the data would appear like this

What I would like to achieve is to collapse the overlapping data so that my query returns
```
**ROW Start End**
0 1 2
1 3 6
2 8 9
```
Is this possible in SQL Server without having to write a complex procedure or statement? | Here's the **[SQL Fiddle](http://www.sqlfiddle.com/#!6/96614/2)** for another alternative.
First, all the limits are sorted by order. Then the "duplicate" limits within an overlapping range are removed (because a Start is followed by another Start or an End is followed by another End). Now, that the ranges are collapsed, the Start and End values are written out again in the same row.
```
with temp_positions as --Select all limits as a single column along with the start / end flag (s / e)
(
select startx limit, 's' as pos from t
union
select endx, 'e' as pos from t
)
, ordered_positions as --Rank all limits
(
select limit, pos, RANK() OVER (ORDER BY limit) AS Rank
from temp_positions
)
, collapsed_positions as --Collapse ranges (select the first limit, if s is preceded or followed by e, and the last limit) and rank limits again
(
select op1.*, RANK() OVER (ORDER BY op1.Rank) AS New_Rank
from ordered_positions op1
inner join ordered_positions op2
on (op1.Rank = op2.Rank and op1.Rank = 1 and op1.pos = 's')
or (op2.Rank = op1.Rank-1 and op2.pos = 'e' and op1.pos = 's')
or (op2.Rank = op1.Rank+1 and op2.pos = 's' and op1.pos = 'e')
or (op2.Rank = op1.Rank and op1.pos = 'e' and op1.Rank = (select max(Rank) from ordered_positions))
)
, final_positions as --Now each s is followed by e. So, select s limits and corresponding e limits. Rank ranges
(
select cp1.limit as cp1_limit, cp2.limit as cp2_limit, RANK() OVER (ORDER BY cp1.limit) AS Final_Rank
from collapsed_positions cp1
inner join collapsed_positions cp2
on cp1.pos = 's' and cp2.New_Rank = cp1.New_Rank+1
)
--Finally, subtract 1 from Rank to start Range #'s from 0
select fp.Final_Rank-1 seq_no, fp.cp1_limit as starty, fp.cp2_limit as endy
from final_positions fp;
```
You can test the result of each CTE and trace the progression. You can do this by removing the following CTE's and selecting from the preceding one, as below, for example.
```
with temp_positions as --Select all limits as a single column along with the start / end flag (s / e)
(
select startx limit, 's' as pos from t
union
select endx, 'e' as pos from t
)
, ordered_positions as --Rank all limits
(
select limit, pos, RANK() OVER (ORDER BY limit) AS Rank
from temp_positions
)
select *
from ordered_positions;
``` | The key to doing this is to assign a "grouping" value to overlapping segments. You can then aggregate by this column to get the information you want. A segment starts a group when it doesn't overlap with an earlier segment.
```
with starts as (
select t.*,
(case when exists (select 1 from table t2 where t2.start < t.start and t2.end >= .end)
then 0
else 1
end) as isstart
from table t
),
groups as (
select s.*,
(select sum(isstart)
from starts s2
where s2.start <= s.start
) as grouping
from starts s
)
select row_number() over (order by min(start)) as row,
min(start) as start, max(end) as end
from groups
group by grouping;
``` | SQL - Consolidate Overlapping Data | [
"",
"sql",
"sql-server",
"aggregate",
"overlap",
""
] |
I have a view called "v\_documents" where a i have a field "document\_type\_name" that is based on some fields. However the field is a string with a name.
Now i want all documents where the type name is contained in another table. But...
This work:
```
SELECT * FROM v_documents WHERE document_type_name IN ('PREVENTIVO', 'FATTURA');
```
This not:
```
SELECT * FROM v_documents WHERE document_type_name IN (
SELECT type FROM t_types
);
```
Where `t_types` contains a list of document types and nothing more.
It give me 0 records.
But if i use `=` istead of `IN()` and i return only one record from the subquery it works.
The problem is that if i'm not wrong this code worked before. I don't know what is happening.
P.S The `t_types` table **DON'T HAVE** null values!
**EDIT**: using the subquery in a field seems work. Why in the IN() not?
Here a screen: on the left the subquery used as field, on the right the return records from `SELECT type FROM t_types`

**EDIT 2**: Screen for @MatBailie's answere. But i used a `LEFT JOIN` instead of `LEFT OUTER JOIN` because i get a MySQL error.
 | This is only half an answer, but too long for a comment.
I would begin by using the following query to directly compare what is in each table...
```
SELECT
*
FROM
(
SELECT
CONCAT('[', document_type_name, ']') AS document_type_name
FROM
v_documents
GROUP BY
document_type_name
)
AS documents
FULL OUTER JOIN
(
SELECT
CONCAT('[', type, ']') AS type
FROM
t_types
GROUP BY
type
)
AS types
ON types.type = documents.document_type_name
ORDER BY
COALESCE(document_type_name, type)
```
This will show every type that exists in both tables, with what matches and what doesn't. The concatenation of the `'['` and `']'` will help spot leading/trailing spaces.
I'd love to see the results in your question.
**EDIT :**
And you are *certain* that the following does not work? *(Exactly as is, with no other changes or additions?)*
```
SELECT
*
FROM
v_documents
WHERE
document_type_name IN (SELECT type FROM t_types)
```
If so, I can't explain it. The existence of *any* matches from the first query "proves" *(or so I thought)* that the `IN (SELECT)` version should be fine.
That said, here are some alternatives.
```
SELECT
*
FROM
v_documents
WHERE
EXISTS (SELECT * FROM t_types WHERE t_types.type = v_documents.document_type_name)
```
Or...
```
SELECT
v_documents.*
FROM
v_documents
INNER JOIN
t_types
ON t_types.type = v_documents.document_type_name
```
If there are duplicates in `t_types`, then you need to use this instead...
```
SELECT
v_documents.*
FROM
v_documents
INNER JOIN
(
SELECT type FROM t_types GROUP BY type
)
AS t_types
ON t_types.type = v_documents.document_type_name
```
As a side benefit, as the number of types in `t_types` increases, each of these alternatives will often out perform use of `IN (SELECT)` any way.
**EDIT 2 :**
This shouldn't make any difference that I'm aware of, but what happens if you try this?
```
SELECT
*
FROM
v_documents
WHERE
CONCAT('[', document_type_name, ']')
IN
(SELECT DISTINCT CONCAT('[', type, ']') FROM t_types)
``` | Try this:
```
SELECT * FROM v_documents WHERE UPPER(trim(document_type_name)) IN
( SELECT UPPER(trim(TYPE)) FROM t_types WHERE type IS NOT NULL);
``` | MySQL IN() with subquery stopped working? | [
"",
"mysql",
"sql",
""
] |
I Have 4 tables:
`Position` Table:
```
| Position | PositionId |
| driver | 1 |
| clerk | 2 |
```
`position Skill` table:
```
| SkillId | skill | PositionId |
| 1 | driving | 1 |
| 2 | drifting | 1 |
```
`Worker` table:
```
| Name | WorkerId |
| John | 1 |
| alex | 2 |
```
`Worker skill` table:
```
| skillId | skill | WorkerId |
| 1 | driving | 1 |
| 2 | drifting | 1 |
```
I `join` the `position` table with `position Skill` table
and `worker` table with `worker skill`
What I'm having trouble with is how can I compare the two `joined` tables to have a result of
for example:
I need to know who's `worker` have all the specific skills that the position have
Like:
I Select position with `positionId` of 1 and have the `skillname` of `driving` and `drifting`
I need to get the `Worker` with the same `skills` with `driving` and `drifting` also
so far i got this:
```
var PositionsWithSkills = (from a in db.Client_Customer_Position
where a.ID == position
select new
{
PositionID = a.ID,
RequiredSkills = (from b in db.Client_Customer_Position_Skills
where b.ClientCusPosId == a.ID
select b.SkillName)
}).ToList();
var WorkersWithSkills = (from x in db.Workers
select new
{
workerId = x.ID,
Skills = (from y in db.Worker_Skills
where y.Worker_ID == x.ID
select y.SkillName)
}).ToList();
var PositionWithSkilledWorkers = (from pos in PositionsWithSkills
select new
{
PositionId = pos.PositionID,
Workers = (from worker in WorkersWithSkills
where pos.RequiredSkills.All(skill => worker.Skills.Any(workerSkill => workerSkill == skill))
select worker.workerId)
}).ToList();
```
the two `query` works well.. but the last query where i must compare the two query =.. i cant get the `worker id`
and can i turn this to a `stored proc`? | Sorry if am wrong. What I got to know from your question is you want the workers list satisfying all the skills of the position you pass. If this is what you want you may try this:
```
var workerWithallSkill = (from u in db.workerList join x in db.workerSkillList on u.WorkerId equals x.WorkerId
where ((from y in db.workerSkillList where y.WorkerId == u.WorkerId select y).Count() == (from p in db.positionSkillList where p.PositionId == 1("pass your positionId here") select p).Count())
select u).ToList().Distinct();
```
or if you want to use lambda expression you can use this
```
var workerWithallSkill = (from u in workerList join x in workerSkillList on u.WorkerId equals x.WorkerId where (workerSkillList.Where(y=> y.WorkerId == u.WorkerId).Count() == positionSkillList.Where(p=>p.PositionId == 1).Count()) select u).ToList().Distinct();
```
For more understanding you can try the below code:
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication8
{
class Program
{
static void Main(string[] args)
{
IList<Position> positionList = new List<Position>() {
new Position(){ position="Driver", PositionId=1}
,new Position(){ position="clerk", PositionId=2}
};
IList<PositionSkill> positionSkillList = new List<PositionSkill>() {
new PositionSkill(){ Skill = "driving",skillid = 1,PositionId = 1}
,new PositionSkill(){ Skill = "drifting",skillid = 2,PositionId = 1}
};
IList<Worker> workerList = new List<Worker>() {
new Worker(){ name = "John",WorkerId = 1}
,new Worker(){ name = "alex",WorkerId = 2}
};
IList<WorkerSkill> workerSkillList = new List<WorkerSkill>(){
new WorkerSkill(){Skill = "driving",skillid = 1,WorkerId = 2}
, new WorkerSkill(){Skill = "drifting",skillid = 2,WorkerId = 2}
};
var workerWithallSkill = (from u in workerList join x in workerSkillList on u.WorkerId equals x.WorkerId where (workerSkillList.Where(y => y.WorkerId == u.WorkerId).Count() == positionSkillList.Where(p => p.PositionId == 1).Count()) select u).ToList().Distinct();
foreach (var worker in workerWithallSkill)
{
Console.WriteLine(worker.name);
}
Console.ReadLine();
}
}
public class Position
{
public string position { get; set; }
public int PositionId { get; set; }
}
public class PositionSkill
{
public int skillid { get; set; }
public string Skill { get; set; }
public int PositionId { get; set; }
}
public class Worker
{
public string name { get; set; }
public int WorkerId { get; set; }
}
public class WorkerSkill
{
public int skillid { get; set; }
public string Skill { get; set; }
public int WorkerId { get; set; }
}
}
```
if a worker has skills from different positions the above code will not work, if this is the scenario try the below code:
```
var WorkerPositionSkill = from p in db.positionSkillList join q in db.workerSkillList on p.skillid equals q.skillid select new { posSkill = p, workerSkill = q };
var workerWithallSkill = (from u in db.workerList join x in db.workerSkillList on u.WorkerId equals x.WorkerId where (WorkerPositionSkill.Where(y => y.workerSkill.WorkerId == u.WorkerId && y.posSkill.PositionId == 1).Count() == db.positionSkillList.Where(p => p.PositionId == 1).Count()) select u).ToList().Distinct();
``` | ```
var PositionsWithSkills = (from a in Positions select new {
PositionID = a.PositionId,
RequiredSkills = (from b in PositionSkills where b.PositionId == a.PositionId select b.skillId).ToList()
}).ToList();
var WorkersWithSkills = (from x in Workers select new {
Name = x.Name,
Skills = (from y in WorkerSkills where y.WorkerId == x.WorkerID select y.skillId).ToList()
}).ToList();
var PositionWithSkilledWorkers = (from pos in PositionsWithSkills select new {
PositionId = pos.PositionID,
Workers = (from worker in WorkersWithSkills where pos.RequiredSkills.All(skill => worker.Skills.Any(workerSkill => workerSkill == skill)) select worker.Name).ToList()
}).ToList();
``` | how to compare string linq with sub query with another linq with sub query | [
"",
"sql",
"asp.net-mvc",
"linq",
"linq-to-sql",
""
] |
When I test this request:
```
SELECT
*, ROW_NUMBER() OVER (ORDER BY test1) AS lineNumb
FROM
(SELECT DISTINCT
tab1.test1, tab2.test2
FROM TB_tab1 tab1
JOIN TB_tab2 tab2 ON tab2.test3 = tab1.test3
JOIN TB_tab3 tab3 ON tab3.test4 = tab1.test4
WHERE tab3.test5 != 'test') AS sub
WHERE lineNumb BETWEEN 1 AND 5
```
I get:
> Error: column name invalid : 'lineNumb'. SQLState: S0001 ErrorCode: 207
Why and how can I correct my request? | Why:
You cannot access the aliased lineNumb column in the where clause of your select--it isn't defined in the context.
How to correct:
Use what you have as a subquery or CTE and select from that using your where.
```
SELECT *
FROM (<you existing query without the where>)
WHERE lineNumb <= 5
``` | ```
SELECT *
FROM
(
SELECT *, ROW_NUMBER() OVER (ORDER BY test1) AS lineNumb FROM (
SELECT DISTINCT tab1.test1, tab2.test2
FROM TB_tab1 tab1
JOIN TB_tab2 tab2 ON tab2.test3 = tab1.test3
JOIN TB_tab3 tab3 ON tab3.test4 = tab1.test4 WHERE tab3.test5 !='test') as sub
) as sub2
WHERE lineNumb BETWEEN 1 AND 5
``` | ROW_NUMBER and multiple JOIN | [
"",
"sql",
"sql-server",
""
] |
I have trouble building a query which I think is actually quite easy...
I have a simple table where I do a simple count, and when I'm filtering the result with a date, I would like to have zeros where there's no rows instead of no result.
For example:
```
select APP_ID as APPLI, count(ID) as NB
from ARCHIVE
where GROUP_ID = 'Sample'
GROUP BY APP_ID
```
returns
```
A 560
B 1,178
C 9
D 643
E 4
```
and
```
select APP_ID as APPLI, count(ID) as NB
from ARCHIVE
where GROUP_ID = 'Sample' and TIMESTAMP > TO_DATE('01/01/2014','dd/mm/yyyy')
GROUP BY APP_ID
```
returns
```
B 40
D 82
E 4
```
And I would like
```
A 0
B 40
C 0
D 82
E 4
```
Some sample datas:
```
ID APP_ID TIMESTAMP
ARCH_1/20/216 A 2010-12-16
ARCH_1/20/218 A 2010-12-16
ARCH_1/20/219 A 2010-12-16
ARCH_1/40/28 A 2011-02-09
ARCH_1/40/29 A 2011-02-09
ARCH_1/40/30 A 2011-02-09
ARCH_1/260/9012 B 2014-04-19
ARCH_1/260/7093 B 2014-04-12
ARCH_1/260/8996 B 2014-04-19
ARCH_1/44/61 C 2011-09-12
ARCH_1/44/62 C 2011-09-13
ARCH_1/260/8382 D 2014-04-16
ARCH_1/260/6872 D 2014-04-11
ARCH_1/260/6271 D 2014-04-08
ARCH_1/260/8607 D 2014-04-17
ARCH_1/260/8998 E 2014-04-19
ARCH_1/260/9011 E 2014-04-19
```
Edit: I'm using Oracle SQL | In order to make this work, you need a (distinct) list of **all** ids first. In situations like this, a subquery is preferred:
```
SELECT Archive_List.app_id, COALESCE(COUNT(), 0) as NB
FROM (SELECT DISTINCT app_id
FROM Archive) Archive_List
LEFT JOIN Archive
ON Archive.app_id = Archive_List.app_id
AND Archive.group_id = 'Sample'
AND Archive.timestamp >= CAST('2014-01-01' as DATE)
GROUP BY Archive_List.app_id
```
If `timestamp` actually *is* the indicated type (and that's a **terrible** name for a column, by the way), you should be using `>=`, so you get any rows set at midnight.
This statement will work on most/all RDBMSs | Try this:
```
select A1.APP_ID as APPLI, NVL(count(A2.ID),0) as NB
from ARCHIVE A1 LEFT JOIN
ARCHIVE A2 on A1.APP_ID=A2.APP_ID
where A1.GROUP_ID = 'Sample' and A1.TIMESTAMP > TO_DATE('01/01/2014','dd/mm/yyyy')
GROUP BY A1.APP_ID
``` | Return zero if there are no results | [
"",
"sql",
"oracle",
""
] |
I need an SQL function to calculate age. It has to be accurate and cover all corner cases.
It is for hospital ward for babies, so age of 30 minuets is a common case.
I have a looked on other answers but could not find one that deals with all cases.
For example:
* Baby born in 2014-04-29 12:59:00.000.
* And now is 2014-04-29 13:10:23.000,
Age should be 0 Years, 0 Months, 0 Days, 0 Hours, **11 minutes**
It would be great if someone can provide the ultimate and definitive version of that function.
(I am afraid that simple **solutions with DateDiff are not good enough**. As stated in a more popular [question](https://stackoverflow.com/questions/57599/how-to-calculate-age-in-t-sql-with-years-months-and-days/11139005) : "The Datediff function doesn't handle year boundaries well ..." | We can use `DATEDIFF` to get the Year, Month, and Day differences, and then simple division for the Seconds, Minutes, and Hours differences.
I've used `@CurrentDate` to recreate the original request, but `@CurrentDate = GETDATE()` will return the age at time of execution.
```
DECLARE @BirthDate DATETIME
DECLARE @CurrentDate DATETIME
SET @BirthDate = '2014-04-29 12:59:00.000'
SET @CurrentDate = '2014-04-29 13:10:23.000'
DECLARE @DiffInYears INT
DECLARE @DiffInMonths INT
DECLARE @DiffInDays INT
DECLARE @DiffInHours INT
DECLARE @DiffInMinutes INT
DECLARE @DiffInSeconds INT
DECLARE @TotalSeconds BIGINT
-- Determine Year, Month, and Day differences
SET @DiffInYears = DATEDIFF(year, @BirthDate, @CurrentDate)
IF @DiffInYears > 0
SET @BirthDate = DATEADD(year, @DiffInYears, @BirthDate)
IF @BirthDate > @CurrentDate
BEGIN
-- Adjust for pushing @BirthDate into future
SET @DiffInYears = @DiffInYears - 1
SET @BirthDate = DATEADD(year, -1, @BirthDate)
END
SET @DiffInMonths = DATEDIFF(month, @BirthDate, @CurrentDate)
IF @DiffInMonths > 0
SET @BirthDate = DATEADD(month, @DiffInMonths, @BirthDate)
IF @BirthDate > @CurrentDate
BEGIN
-- Adjust for pushing @BirthDate into future
SET @DiffInMonths = @DiffInMonths - 1
SET @BirthDate = DATEADD(month, -1, @BirthDate)
END
SET @DiffInDays = DATEDIFF(day, @BirthDate, @CurrentDate)
IF @DiffInDays > 0
SET @BirthDate = DATEADD(day, @DiffInDays, @BirthDate)
IF @BirthDate > @CurrentDate
BEGIN
-- Adjust for pushing @BirthDate into future
SET @DiffInDays = @DiffInDays - 1
SET @BirthDate = DATEADD(day, -1, @BirthDate)
END
-- Get number of seconds difference for Hour, Minute, Second differences
SET @TotalSeconds = DATEDIFF(second, @BirthDate, @CurrentDate)
-- Determine Seconds, Minutes, Hours differences
SET @DiffInSeconds = @TotalSeconds % 60
SET @TotalSeconds = @TotalSeconds / 60
SET @DiffInMinutes = @TotalSeconds % 60
SET @TotalSeconds = @TotalSeconds / 60
SET @DiffInHours = @TotalSeconds
-- Display results
SELECT @DiffInYears AS YearsDiff,
@DiffInMonths AS MonthsDiff,
@DiffInDays AS DaysDiff,
@DiffInHours AS HoursDiff,
@DiffInMinutes AS MinutesDiff,
@DiffInSeconds AS SecondsDiff
``` | This query will give you date diff in minutes,
```
select datediff(mi, '2014-04-23 05:23:59.660',getdate())
```
Then you can simply calc the `minutes/60` for `hours` and `minutes mod 60` for `minutes`
```
select datediff(mi, '2014-04-23 05:23:59.660',getdate())/60 as [Hours], select datediff(mi, '2014-04-23 05:23:59.660',getdate()) % 60 as [Minutes]
``` | MS SQL Server : calculate age with accuracy of hours and minuets | [
"",
"sql",
"sql-server",
"datetime",
"datediff",
""
] |
I have a view in SQL Server which uses dates to determine which tables to access data from. The problem is it only seems to work when given the date as a `varchar` like `'20120423'`.
So I am trying to dynamically create this date with `GETDATE()` instead of having to use the typed out version. When I run the top `SELECT` statement it returns `'20120423'` like I would expect but when I try to compare the two values they are not equal and the `IF` statement prints `'VALUES ARE NOT THE SAME'`.
```
SELECT
'''' +CONVERT(VARCHAR(8), DateAdd(YY,-2,GETDATE()), 112) +''''
IF '''' +CONVERT(VARCHAR(8), DateAdd(YY,-2,GETDATE()), 112) +'''' = '20120423'
BEGIN
PRINT 'VALUES ARE THE SAME'
END
ELSE
BEGIN
PRINT 'VALUES ARE NOT THE SAME'
END
```
I'm kind of lost as to where to go from here. Thanks for any help.
**EDIT**:
With the answers given then these two queries should be the same even though they are treated differently by my view.
```
SELECT *
FROM DatesView
WHERE Timestamp > CONVERT(VARCHAR(8), DateAdd(YY,-2,GETDATE()), 112)
SELECT *
FROM DatesView
WHERE Timestamp > '20120423'
```
The top one looks through all tables where the bottom one correctly only searches the necessary tables. | You're getting thrown off by the quote marks, just remove them they are unnecessary.
```
SELECT CONVERT(VARCHAR(8), DateAdd(YY,-2,GETDATE()), 112)
IF CONVERT(VARCHAR(8), DateAdd(YY,-2,GETDATE()), 112) = '20120423'
BEGIN
PRINT 'VALUES ARE THE SAME'
END
ELSE
BEGIN
PRINT 'VALUES ARE NOT THE SAME'
END
``` | Delete the first two `'`. Try this.
You are comparing `'20120423'=20120423`
```
SELECT '' +CONVERT(VARCHAR(8), DateAdd(YY,-2,GETDATE()), 112) +''
IF '' +CONVERT(VARCHAR(8), DateAdd(YY,-2,GETDATE()), 112) +'' = '20120423'
BEGIN
PRINT 'VALUES ARE THE SAME'
END
ELSE
BEGIN
PRINT 'VALUES ARE NOT THE SAME'
END
``` | Convert datetime to string/varchar in SQL Server | [
"",
"sql",
"sql-server",
"date",
""
] |
I have the below data.
```
0:00:00
0:30:00
1:00:00
1:30:00
2:00:00
2:30:00
3:00:00
3:30:00
4:00:00
4:30:00
5:00:00
5:30:00
6:00:00
6:30:00
```
I can extract the hour the using `EXTRACT(HOUR FROM TIMESTAMP)` but this will give me 24 hours.
But now I need to some different calculation where I can get numbers from `1-48` based on the time given.
Something like this:
```
0:00:00 1
0:30:00 2
1:00:00 3
1:30:00 4
2:00:00 5
2:30:00 6
3:00:00 7
3:30:00 8
4:00:00 9
4:30:00 10
6:00:00 13
6:30:00 14
```
Note the skipped 11 and 12, for the absent values 5:00 and 5:30.
Is there any possibilities that I can get that result in PostgreSQL? | Simply use formula **`1 + extract(hour from 2 * tm)`** - it gives your expected result exactly - obligatory [**SQLFiddle**](http://sqlfiddle.com/#!15/a193d/1). | This will give you a `double precision` result, that you can round to whatever you want:
```
2 * (EXTRACT(HOUR FROM t) + EXTRACT(MINUTE FROM t) / 60) + 1
```
**EDIT**:
Or, as @CraigRinger suggested:
```
EXTRACT(EPOCH FROM t) / 1800 + 1
```
For the later, `t` needs to be `TIME`, **not** `TIMESTAMP`. Use cast if needed.
**UPDATE**: This will work with `INTERVAL`s too.
```
SELECT 2 * (EXTRACT(HOUR FROM t) + EXTRACT(MINUTE FROM t) / 60) + 1,
EXTRACT(EPOCH FROM t) / 1800 + 1
FROM (VALUES (time '4:30:00'), (time '7:24:31'), (time '8:15:00')) as foo(t)
-- results:
?column? | ?column?
---------+---------
10 | 10
15.8 | 15.8172222222222
17.5 | 17.5
```
But as you wrote, there will be no edge cases (when the time cannot be divided with 30 minutes). | Extract hours as 1 - 48 from half hour interval times | [
"",
"sql",
"database",
"postgresql",
"date-arithmetic",
""
] |
I have two databases in the same server and I need to:
```
Select from table1 (in database1) the id field
Where notific1=1
```
But only the `user_id` list
```
Where in table2 (in database2) the enabled field=1
```
Being the user\_id field in the two tables the same.
I tried:
```
SELECT table1.id
FROM [database1].[dbo].[table1] as users
INNER JOIN [database2].[dbo].[table2] as subs
ON users.user_id=subs.user_id
WHERE users.notific1=1 AND
WHERE subs.enabled=1
```
This is throwing the error:
> .#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '[database1].[dbo].[table1] as users INNER JOIN [database2].[dbo]' at line 2
NOTE: I'm using MySQL | You can not have 2 where as you did ( since you tagged your question with Mysql)
```
WHERE users.notific1=1 AND
WHERE subs.enabled=1
```
It should be
```
WHERE
users.notific1=1
AND
subs.enabled=1
```
Also while JOINING the 2 databases the syntax is
```
select * from proj1.users as y
inner join project2.users f on f.email = y.email
and y.email = 'abhik@xxxx.com'
```
`proj1` and `project2` are 2 databases in the same server and `users` is the tables in those databases. | For mysql, the `square brackets []` are not used for object names.
Use back ticks instead
```
SELECT table1.id
FROM `database1`.`table1` as users
INNER JOIN `database2`.`table2` as subs
ON users.user_id=subs.user_id
WHERE users.notific1=1 AND
subs.enabled=1
``` | Query two databases in the same server | [
"",
"mysql",
"sql",
""
] |
Here is my query:
```
SELECT
dateTime,
AVG([timeTaken]) as avgtime,
MAX([timeTaken]) as maxtime,
COUNT(*) totalcalls
FROM
[Logs]
WHERE
csUriStem = '/REST/Issues/Issues.svc/' AND
[dateTime] > DATEADD(MINUTE, -15, GETUTCDATE()) AND
(csUserAgent != 'Fiddler' OR csUserAgent IS NULL)
```
I get this error when executed:
> Msg 8120, Level 16, State 1, Line 2
> Column 'Logs.dateTime' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
I understand why, but my question is, how do I get the associated `DateTime` to the corresponding `[MAX([timeTaken]) as maxtime]`? | Okay, so aggregate functions like `AVG`, `MAX`, and `COUNT` will require some sort of `GROUP BY` if there are other fields in the `SELECT` list. This is how they know what *subset* to operate on. So what you would need to do, to get this to *run*, is something like this:
```
SELECT dateTime,
AVG([timeTaken]) as avgtime,
MAX([timeTaken]) as maxtime,
COUNT(*) totalcalls
FROM [Logs]
WHERE
csUriStem = '/REST/Issues/Issues.svc/' AND
[dateTime] > DATEADD(MINUTE, -15, GETUTCDATE()) AND
(csUserAgent != 'Fiddler' OR csUserAgent IS NULL)
GROUP BY dateTime
```
However, that may, *or may not*, be what you want. This is going to perform the `AVG`, `MAX`, and `COUNT` *over* every grouping of `dateTime`.
However, this grouping of `dateTime` is probably illogical; you probably want something like this:
```
SELECT CONVERT(VARCHAR(8), dateTime, 101) AS groupDate,
AVG([timeTaken]) as avgtime,
MAX([timeTaken]) as maxtime,
COUNT(*) totalcalls
FROM [Logs]
WHERE
csUriStem = '/REST/Issues/Issues.svc/' AND
[dateTime] > DATEADD(MINUTE, -15, GETUTCDATE()) AND
(csUserAgent != 'Fiddler' OR csUserAgent IS NULL)
GROUP BY CONVERT(VARCHAR(8), dateTime, 101)
```
That will format that grouping date by `mm/dd/yy`.
To further consider what's actually going on with aggregate functions, if you *didn't* have any additional fields:
```
SELECT AVG([timeTaken]) as avgtime,
MAX([timeTaken]) as maxtime,
COUNT(*) totalcalls
FROM [Logs]
WHERE
csUriStem = '/REST/Issues/Issues.svc/' AND
[dateTime] > DATEADD(MINUTE, -15, GETUTCDATE()) AND
(csUserAgent != 'Fiddler' OR csUserAgent IS NULL)
```
it still operates over a *group.* That *group* just happens to be the *entire* result set. | You need to include it in a group by clause
Something like this.
```
SELECT
dateTime,
AVG([timeTaken]) as avgtime,
MAX([timeTaken]) as maxtime,
COUNT(*) totalcalls
FROM
[Logs]
WHERE
csUriStem = '/REST/Issues/Issues.svc/' AND
[dateTime] > DATEADD(MINUTE, -15, GETUTCDATE()) AND
(csUserAgent != 'Fiddler' OR csUserAgent IS NULL)
GROUP BY
dateTime;
```
Note if you want information on the average and max seperately then you need to split up the query into two separate queries. Then merge them after. | How do I add a column into a aggregate function | [
"",
"sql",
"aggregate",
""
] |
I'm a bit of a noobie when it come to SQL, I'm using Access 2013 and I'm trying to update a date field in one table, using id numbers from a different table to only update specific ones.
The query I have is:
```
UPDATE Leadsavailable SET First_Usage_Date = '23/04/2014'
from leadsavailable r
inner join WorkingTable_GOSH g
on g.[lead number] = r.[Lead number]
where g.Type = 'GOSH'
```
but I keep getting errors and don't know why.
Any help would be much appreciated | Try this sorry im in a mobile:
```
UPDATE Leadsavailable A
INNER JOIN WorkingTable_GOSH B
ON A.[lead number] = B.[Lead number]
Set A.[First_Usage_Date] = '23/04/2014'
Where B.Type = 'GOSH';
``` | Assuming my understanding of your requirement is correct, and you want to update all records in `Leadsavailable` that have a matching record in `WorkingTable_GOSH` with `Type = 'GOSH'` then this will give you the results you're after:
```
UPDATE Leadsavailable
SET First_Usage_Date = '23/04/2014'
WHERE [lead number] in (SELECT [Lead number]
FROM WorkingTable_GOSH
WHERE Type = 'GOSH')
``` | Syntax error when updating | [
"",
"sql",
"ms-access-2013",
""
] |
I'm having trouble filling my database with plenty of records to do a speed test. Can anybody tell me which query should be faster when dealing with millions of records? I like Tomas' query the most, but won't the DISTINCT be slowing it down a lot when dealing with a bigger table?
I am surprised to see that my subquery does not slow things down as much as I thought it would.
:: Mine. Producing 22 rows in 00.0640419 > 00.1030255 seconds.
```
SELECT
[planning].[id] as planningId,
[planning].[type] as planningType,
[planning].[from] as planningFrom,
[planning].[till] as planningTill,
[worker].[intId] as workerId,
[worker].[name] as workerName,
[site].[intId] as siteId,
[site].[name] as siteName
FROM
[worker]
LEFT JOIN [planning] ON [planning].[workerId] = [worker].[intId] AND [planning].[companyId] = [worker].[companyId]
LEFT JOIN [site] ON [planning].[siteId] = [site].[intId] AND [planning].[companyId] = [site].[companyId]
WHERE
[worker].[companyId] = 2
AND ( [planning].[id] IS NULL OR ( [planning].[from] <= '2014-04-30' AND [planning].[till] >= '2014-04-01') )
AND ([worker].[intId] IN (
SELECT
[worker].[intId]
FROM
[planning]
INNER JOIN [worker] ON [planning].[workerId] = [worker].[intId] AND [planning].[companyId] = [worker].[companyId]
WHERE
[worker].[companyId] = 2
AND ([planning].[type] = 'absent' OR ([planning].[siteId] IN ('7710122')))
) OR [worker].[intId] IN ('7701260')
)
```
:: Sirko. Producing 22 rows in 00.0684108 > 00.0955292 seconds.
```
SELECT
[planning].[id] as planningId,
[planning].[type] as planningType,
[planning].[from] as planningFrom,
[planning].[till] as planningTill,
[worker].[intId] as workerId,
[worker].[name] as workerName,
[site].[intId] as siteId,
[site].[name] as siteName
FROM
[worker]
LEFT JOIN [planning] ON [planning].[workerId] = [worker].[intId] AND [planning].[companyId] = [worker].[companyId]
LEFT JOIN [site] ON [planning].[siteId] = [site].[intId] AND [planning].[companyId] = [site].[companyId]
LEFT JOIN ( SELECT DISTINCT
[worker].[intId]
FROM
[planning]
LEFT JOIN [worker] ON [planning].[workerId] = [worker].[intId] AND [planning].[companyId] = [worker].[companyId]
WHERE
[worker].[companyId] = 2
AND ([planning].[type] = 'absent' OR ([planning].[type] = 'site' AND [planning].[siteId] IN ('7710122')))
) AS filter ON filter.[intId] = [worker].[intId]
WHERE
[worker].[companyId] = 2
AND ( ( [planning].[from] <= '2014-04-30' AND [planning].[till] >= '2014-04-01') OR [worker].[intId] IN ('7701260') )
```
:: Tomas Pastircak. Producing 22 rows in 00.0674178 > 00.0850567 seconds.
```
SELECT DISTINCT
[planning].[id] as planningId,
[planning].[type] as planningType,
[planning].[from] as planningFrom,
[planning].[till] as planningTill,
[worker].[intId] as workerId,
[worker].[name] as workerName,
[site].[intId] as siteId,
[site].[name] as siteName
FROM
[worker]
LEFT JOIN [planning] ON [planning].[workerId] = [worker].[intId] AND [planning].[companyId] = [worker].[companyId]
LEFT JOIN [site] ON [planning].[siteId] = [site].[intId] AND [planning].[companyId] = [site].[companyId]
LEFT JOIN [planning] p2 ON p2.[workerId] = [worker].[intId] AND p2.[companyId] = [worker].[companyId]
WHERE
[worker].[companyId] = 2
AND ( [planning].[id] IS NULL OR ( [planning].[from] <= '2014-04-30' AND [planning].[till] >= '2014-04-01') )
AND (p2.[type] = 'absent' OR p2.[siteId] IN ('7710122') OR [worker].[intId] IN ('7701260'))
``` | Is there a reason why couldn't you just add it to the WHERE conditions, without all the subquery stuff? It seems to return the same data...
```
SELECT
...
FROM
...
LEFT JOIN [planning] p2 ON p2.[workerId] = [worker].[intId] AND p2.[companyId] = [worker].[companyId]
WHERE
[worker].[companyId] = 2
AND ( [planning].[id] IS NULL OR ( [planning].[from] <= '2014-04-30' AND [planning].[till] >= '2014-04-01') )
AND (p2.[type] = 'absent' OR (p2.[type] = 'site' AND p2.[siteId] IN ('7710122'))
``` | I'm not exactly familiar with T-SQL syntax, but something like the following should work:
```
SELECT
[planning].[id] as planningId,
[planning].[type] as planningType,
[planning].[from] as planningFrom,
[planning].[till] as planningTill,
[planning].[busyMon] as busyMon,
[planning].[busyTue] as busyTue,
[planning].[busyWed] as busyWed,
[planning].[busyThu] as busyThu,
[planning].[busyFri] as busyFri,
[planning].[busySat] as busySat,
[planning].[busySun] as busySun,
[planning].[busyHolidays] as busyHolidays,
[worker].[intId] as workerId,
[worker].[name] as workerName,
[worker].[partner] as workerPartner,
[site].[intId] as siteId,
[site].[name] as siteName
FROM
[worker]
LEFT JOIN [planning] ON [planning].[workerId] = [worker].[intId] AND [planning].[companyId] = [worker].[companyId]
LEFT JOIN [site] ON [planning].[siteId] = [site].[intId] AND [planning].[companyId] = [site].[companyId]
LEFT JOIN ( SELECT DISTINCT
[worker].[intId]
FROM
[planning]
LEFT JOIN [worker] ON [planning].[workerId] = [worker].[intId] AND [planning].[companyId] = [worker].[companyId]
WHERE
[worker].[companyId] = 2
AND ([planning].[type] = 'absent' OR ([planning].[type] = 'site' AND [planning].[siteId] IN ('7710122','123456')))
) AS filter ON filter.[intId] = [worker].[intId] OR [worker].[intId] IN ('987654','654321')
WHERE
[worker].[companyId] = 2
AND ( [planning].[id] IS NULL OR ( [planning].[from] <= '2014-04-30' AND [planning].[till] >= '2014-04-01') )
``` | SQL - To subquery or not to subquery? | [
"",
"sql",
"t-sql",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.