Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have this SQL commands, which I would like to run in one command. But if I remove the semicolon from between them, then it doesn't works anymore;
```
UPDATE runners SET money=20000
WHERE rrank >= 3;
UPDATE runners SET money=25000
WHERE nev = 'Master';
``` | Partial (however generalized) solution (if `runners` is not *that big table*)
```
update runners
set money = case
when rrank >= 3 then
20000
when nev = 'Master' then
25000
-- any number of when here
-- if no when applied, do nothing
else
money
end
``` | Combine the logic into a single update:
```
UPDATE runners
SET money = (case when nev = 'Master' then 25000
else 20000
end)
WHERE rrank >= 3 or nev = 'Master';
``` | How to run more SQL updates in one SQL command? | [
"",
"mysql",
"sql",
""
] |
I have a table named 'country' with a column named 'name'
and the names in this column appears with translation followed by special character '/'.
```
IRELAND/IRLANDE
GREECE/GRÈCE
DENMARK/DANEMARK
```
Now i want only the countrynames before this special character'/' so the out put should look like this..
```
IRELAND
GREECE
DENMARK
```
please help. Thanks in advance | ```
create table #t(name nvarchar(40))
insert into #t values('IRELAND/IRLANDE')
,('GREECE/GRÈCE')
,('DENMARK/DANEMARK')
select substring(name,0,CHARINDEX('/',name)) from #t
``` | Why LEN(names)-CHARINDEX('/',names)?
try using CHARINDEX('/',names)+1 instead.
As far as I remember, SUBSTRING's third variables should be the length of the desired output string. | How to remove text followed by a special characted in MSQL | [
"",
"sql",
"substring",
"special-characters",
"trim",
"charindex",
""
] |
I need to implement custom ordering for my table. For example I have a table called "TestTest" with values: `a, d01, d04, d02, b` . I need to select data and order them so that values with "d" will be first and rest will be sorted alphanumerical. So the result would be `d01,d02,d03,a,b`
Script to create and insert data:
```
CREATE TABLE TestTest(
Name varchar(200)
)
DELETE FROM TestTest
INSERT INTO TestTest( Name )
VALUES( 'a' )
INSERT INTO TestTest( Name )
VALUES( 'd01');
INSERT INTO TestTest( Name )
VALUES( 'd04');
INSERT INTO TestTest( Name )
VALUES( 'd02');
INSERT INTO TestTest( Name )
VALUES( 'b' );
```
Thx for any help ;) | ```
Select *
From TestTest
Order By CASE WHEN LEFT(Name,1)='d' THEN 1 ELSE 2 END,Name
```
[**SQL Fiddle Demo**](http://www.sqlfiddle.com/#!3/ef9e7/1) | Quick soution:
```
Select *
from TestTest
order by case when Name like 'd%' then 'aaaaa'+Name else Name end
``` | Custom ordering in TSQL | [
"",
"sql",
"t-sql",
""
] |
I am in the process of converting some Access queries into tsql and this error pops up when I try to execute the query.
I am guessing that SQL Server does not allow adding of 'bit' types, so I found the cultprit lines where that occurs and they are:
```
SELECT DISTINCT
[modules].[b]+[modules].[w]+[modules].[e]+[modules].[j]+
[modules].[p]+[modules].[s] AS approvalRating, -- other columns here --
```
And:
```
ORDER BY [modules].[b]+[modules].[w]+[modules].[e]+[modules].[j]+
[modules].[p]+[modules].[s],
modulePriority.configPriority,
[modulePositionalData].[highPos]-[modulePositionalData].[lowPos]+1,
modulePositionalData.iMax;
```
Now I did not create the original Access queries and I have no idea what was the intention of adding that Boolean fields which makes it a bit problematic, but is there a way to allow the operations to be performed and result to be the same as performed by Access? | you can't add bit fields in sql server
But you can cast them to int
so
```
CAST(yourBitField as int) + CAST (yourSecondBitField as int)
```
By the way (would say it's due to [type preference order](http://technet.microsoft.com/en-us/library/aa258264%28v=sql.80%29.aspx)), it will be ok if you cast only one of them
```
CAST(yourBitField as int) + yourSecondBitField
```
But casting all is probably "easier to read and understand". | You cannot add bits in SQL Server, as they can only be 0 or 1. You can however convert them to integer values first and then add them. To convert a bit to an int, use the CAST function:
```
CAST([modules].[b] AS INT) + CAST([modules].[w] AS INT) + CAST([modules].[e] AS INT) ... etc
```
See more on SQL Server type conversion here: <http://msdn.microsoft.com/en-us/library/ms187928.aspx> | TSQL error: Operand data type bit is invalid for add operator | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have an array of IDs:
```
[1, 2, 3, 4, 5, 6]
```
To check what records exist in the table I execute this query:
```
SELECT id FROM table WHERE id in (1, 2, 3, 4, 5, 6);
```
The query returns an `id` of every existing record but what if I want to know what records don't exist? For instance if a record with `id: 1` doesn't exist I want this `id` to be returned. How can I do this? | ```
select idlist.id
from (
select 1 as id
union all select 2
union all select 3
union all select 4
union all select 5
union all select 6
) as idlist
left join the_table
on idlist.id = the_table.id
where the_table.id is null;
```
SQLFiddle example: <http://sqlfiddle.com/#!2/b3a5b/1> | ```
select id from table where id not in(1,2,3,4,5,6)
``` | Return id of a non-existing record | [
"",
"mysql",
"sql",
""
] |
Have a question about a query I am attempting to write, using SQL Server 2012. I have a table with 2 columns (Agent and UN) I am focusing on. I would like to find the number off occurrences that Agent and UN occur. For example, in the table below:
```
+----+-------+----+
| ID | Agent | UN |
+----+-------+----+
| 1 | 27 | 1 |
| 2 | 28 | 1 |
| 3 | 27 | 1 |
| 4 | 27 | 2 |
| 5 | 28 | 2 |
| 6 | 28 | 2 |
+----+-------+----+
```
An example would look similar to this:
```
+-------+--------+----+
| Count | Agent | UN |
+-------+--------+----+
| 2 | 27 | 1 |
| 2 | 28 | 2 |
| 1 | 27 | 2 |
| 1 | 28 | 1 |
+-------+--------+----+
```
The ID does not matter, I just want to get where Agent and UN occur as pairs and their counts.
My attempt was this. I would have to do this for every agent and then combine them, but I'm thinking there is probably a quicker way to accomplish this?
```
select count(UN) as Count, Agent, UN
Where Agent = 27
group by UN
order by count(UN) desc
``` | Group by both agent and UN, and take out the condition from the where clause, to get the count for all groups.
```
select count(*), agent, un
from tbl
group by agent, un
order by 1 desc
``` | You should `GROUP BY` `UN` and `Agent` and then `COUNT` duplicates. To retrieve data for all possible values in `Agent` column you should remove your `WHERE` clause :
```
SELECT COUNT(*) as Count
, Agent
, UN
FROM table
GROUP BY UN
, Agent
ORDER BY COUNT(*) DESC
``` | Get count of multiple column occurrences in SQL | [
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
I am trying to update the data in a particular column according to the data in another column.
Some thing like below.
```
Name ImageName
---------- -----------
aaa no_image.jpg
bbb no_image.jpg
ccc no_image.jpg
ddd no_image.jpg
```
I like to update this table something like below.
```
Name ImageName
---------- -----------
aaa aaa.jpg
bbb bbb.jpg
ccc ccc.jpg
ddd ddd.jpg
```
Please find the sqlfiddle from the following link.
[SqlFiddle Link](http://www.sqlfiddle.com/#!2/6e238/2) | You could simply do this in an `UPDATE` query itself.
Try this:
```
UPDATE table1
SET ImageName=Name+'.jpg'
``` | ```
Update table1
set imagename= name+'.jpg';
``` | Updating a column in sql | [
"",
"sql",
""
] |
I have a table with Names and university courses, with each course registered being a different entry in the table
```
NAME COURSE
StudA Bio
StudA Maths
StudB Maths
StudC Bio
StudC Maths
```
How can I select all students registered for both Bio and Maths? I Tried
```
SELECT * FROM Table WHERE Course = 'Bio' And Course = 'Maths' GROUP BY Name;
```
But I get no results.
I need BOTH the results to the same student. i.e Only StudA and B should be given as they are registred for BOTH courses. | It depends on what you mean, are you looking for students registered for both math and bio, or for student registered in either of them?
-- Student registered on both math and bio
```
select NAME
from T
where Course IN('Bio', 'Maths')
group by NAME
having count( distinct COURSE ) = 2
``` | Use `OR` instead of `AND`:
```
SELECT *
FROM Table
WHERE Course = 'Bio' OR Course = 'Maths'
GROUP BY Name;
```
`AND` returns records with Course='Bio' **and** 'Maths' (which won't happen at the same time).
Example in [**SQL Fiddle**](http://www.sqlfiddle.com/#!2/e34bd/5).
If you are looking for students who appear for both courses:
```
SELECT *
FROM TableName
WHERE Course = 'Bio' OR Course = 'Maths'
GROUP BY Name
HAVING COUNT(*)=2
```
Example in [**SQL Fiddle**](http://www.sqlfiddle.com/#!2/e34bd/6). | SQL Selecting with 2 entries in 1 table | [
"",
"mysql",
"sql",
""
] |
Let's I have a inner join which results in a table as follows
```
WORKFLOWID Value
1 One
1 Two
2 Three
2 Four
```
But what I want for this is one record to come back
```
ID Value1 Value2
1 One Two
2 Three Four
```
What options do I have in SQL to change an inner join to behave as above ?
```
SELECT ws.workflow_id as WorkflowId, sg.unmatched_value as UnmatchedValue
FROM [geo_workflow_step] as ws
INNER JOIN [geo_workflow] as gw on ws.workflow_id = gw.id
INNER JOIN [geo_super_group] as sg on gw.super_group_id = sg.ID
order by WorkflowId
``` | ```
select t1.workflowid as id,
min(t1.value) as value1,
max(t2.value) as value2
from the_table t1
join the_table t2
on t1.workflowid = t2.workflowid
and t1.value <> t2.value
group by t1.workflowid
```
This assumes that there are always exactly two rows present in the table. If this is not the case, you will indeed lookup the `PIVOT` operator (search for it, there are tons of questions for that on SO)
SQLFiddle: <http://www.sqlfiddle.com/#!3/97e8b/2> | Try this:
```
WITH CTE AS
(SELECT *,RN=ROW_NUMBER() OVER(PARTITION BY WORKFLOWID ORDER BY WORKFLOWID)
FROM TableName)
SELECT WORKFLOWID,MAX(Value1) as Value1,MAX(Value2) as Value2
FROM
(SELECT WORKFLOWID,
CASE WHEN RN=1 THEN Value END as Value1,
CASE WHEN RN=2 THEN Value END as Value2
FROM CTE) T
GROUP BY WORKFLOWID
```
Result:
```
WORKFLOWID VALUE1 VALUE2
1 One Two
2 Three Four
```
See result in [**SQL Fiddle**](http://www.sqlfiddle.com/#!3/0f137/27). | Get Results from INNER JOIN on same row | [
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
I am trying to order by year ascending/descending however I want when the year is 0 to be treated as the newest.
For example:
```
2013
2014
0
ORDER BY YEAR DESC should be
0
2014
2013
```
After some reading I thought this should work but it doesn't:
```
ORDER BY CASE WHEN YEAR = 0 THEN 9999, YEAR ASC
``` | Please try:
```
select *
from TableName
order by case YEAR when 0 then 9999 else YEAR end desc
```
[SQL Fiddle Demo](http://www.sqlfiddle.com/#!4/7f977e/1) | Try this:
```
SELECT *
FROM TableName
ORDER BY CASE WHEN YEAR = 0 THEN 0 ELSE 1 END, YEAR ASC
```
Result:
```
YEAR
0
2013
2014
```
An example in [**SQL Fiddle**](http://www.sqlfiddle.com/#!3/3018c/1). | SQL case in order by | [
"",
"sql",
"sql-order-by",
"case",
""
] |
I have a simple table -
```
id | date | type | value
-------------------------
1 1/1/14 A 1
2 1/1/14 A 10
3 2/1/14 A 10
4 2/1/14 A 15
5 2/1/14 B 15
6 2/1/14 B 20
```
I would like to create a new column which calculates the minimum value per day per type. So giving the following results -
```
id | date | type | value | min_day
-----------------------------------
1 1/1/14 A 1 1
2 1/1/14 A 10 1
3 2/1/14 A 10 10
4 2/1/14 A 15 10
5 2/1/14 B 15 15
6 2/1/14 B 20 15
```
Is this possible? If so how would I go about it? I've been looking into triggers.
Thanks for any help. | First create a field named `min_day` in your table. Then you can use `JOIN` in an `UPDATE` query.
Try this:
```
UPDATE TableName T1 JOIN
(SELECT date,type,MIN(value) as MinValue
FROM TableName
GROUP BY type,date) T2 ON T1.type=T2.type AND T1.date=T2.date
SET T1.min_day = T2.MinValue
```
An example in [**SQL Fiddle**](http://www.sqlfiddle.com/#!2/32855/9).
**EDIT:**
For day-wise grouping:
```
UPDATE TableName T1 JOIN
(SELECT MONTH(date) as mon,type,MIN(value) as MinValue
FROM TableName
GROUP BY type,MONTH(date)) T2 ON T1.type=T2.type AND MONTH(T1.date)=T2.mon
SET T1.min_day = T2.MinValue
```
Result in [**SQL Fiddle**](http://www.sqlfiddle.com/#!2/28c1e/27). | Assuming that your table's name is mytable, try this:
```
SELECT mt.id,
mt.date,
mt.type,
mt.value,
mt.min_day,
md.min_value
FROM mytable mt
LEFT JOIN
(SELECT date, MIN(value) min_value FROM mytable GROUP BY DATE
) md
ON mt.date=md.date;
``` | Column calculated by column with grouping | [
"",
"mysql",
"sql",
""
] |
So I have this specific table structure
```
State_Code | ColA | ColB | Year | Month
---------- ------ ---- ------ -----
AK 5 3 2013 4
AK 6 1 2014 8
AK 3 4 2012 9
.
.
.
.
.
```
I do not have access to change the table structure.
The required query is described as follows
Find total ColA, ColB for each state between the last 12 months and the last 24 months.
**Questions**
Is it possible to get such a query done without using stored procedures.
I can frame a query using add\_months for getting the right year, but I can't get around the logical issue of selecting the month range. | *Community Wiki because it is borrowing heavily from other answers.*
The [answer](https://stackoverflow.com/a/23627359/15168) by [Farhad Jabiyev](https://stackoverflow.com/users/1576032/farhad-jabiyev) (now deleted — see [Is it OK to unaccept an accepted answer after weeks](https://meta.stackoverflow.com/questions/256585/is-it-ok-to-unaccept-an-answer-after-weeks)) was:
```
SELECT STATE_CODE, SUM(COLA) SUM_COLA, SUM(COLB) SUM_COLB
FROM TABLE_NAME
WHERE to_date(ExtractDay(sysdate) || MONTH || YEAR, 'ddMMyyyy')
between add_months(sysdate,-12) AND add_months(sysdate,-24)
GROUP BY STATE_CODE;
```
This answer runs into problems when the current date is at the end of the month for some intervals (with the -24..-12 month range, usually only on a Leap Day, but for other ranges of months, it can run into problems from the 29th of the month onwards).
However, it is firmly on the right track and only needs (relatively) trivial fixing. The requirement is to get the year/month combination for the current month minus 12 months and the current month minus 24 months.
* Change the 'day of month' from `ExtractDay(sysdate)` to `'01'` of month (since the data stored only has one month granularity and every month has a first of the month, but not every month has a 29th, 30th or 31st).
If you use dates, then you need to get the first day of the current month (twice) which is verbose:
```
SELECT STATE_CODE, SUM(COLA) SUM_COLA, SUM(COLB) SUM_COLB
FROM TABLE_NAME
WHERE to_date('01' || MONTH || YEAR, 'ddMMyyyy')
BETWEEN to_date('01' || ExtractMonth(add_months(sysdate, -24)) ||
ExtractYear(add_months(sysdate, -24)), 'ddMMyyyy')
AND to_date('01' || ExtractMonth(add_months(sysdate, -12)) ||
ExtractYear(add_months(sysdate, -12)), 'ddMMyyyy')
GROUP BY STATE_CODE;
```
Alternatively, and probably better (if only because simpler) is to convert the year/month combination as suggested by [Gordon Linoff](https://stackoverflow.com/users/1144035/gordon-linoff) in his [answer](https://stackoverflow.com/a/23630042/):
```
SELECT STATE_CODE, SUM(COLA) SUM_COLA, SUM(COLB) SUM_COLB
FROM TABLE_NAME
WHERE (MONTH + 100 * YEAR)
BETWEEN (ExtractMonth(add_months(sysdate, -24)) + 100 *
ExtractYear(add_months(sysdate, -24)))
AND (ExtractMonth(add_months(sysdate, -12)) + 100 *
ExtractYear(add_months(sysdate, -12))
GROUP BY STATE_CODE;
```
Some residual issues to note:
1. The standard behaviour of *x* BETWEEN *y* AND *z* requires that *y* is less than or equal to *z*. That is, `x BETWEEN y AND z` is equivalent to `x >= y AND x <= z`. (Is there any DBMS that treats it as equivalent to `x >= MIN(y, z) AND z <= MAX(y, z)`?) Hence the code above switches -12 and -24 so the the range is correct.
2. The bounds of *x* BETWEEN *y* AND *z* are inclusive, so the -24 to -12 range covers 13 months, not 12 months. As long as that's what you want, it's fine. Otherwise, you probably need -24..-13 or maybe -23..-12.
3. You may be able to use functions `YEAR()` and `MONTH()` in lieu of `ExtractYear()` and `ExtractMonth()`. You might need to worry about ambiguity between column names `Year` and `Month` and functions of the same name. Whether this matters will depend on the DBMS.
This question does highlight that date arithmetic is tricky stuff, and leap years and ends of months always have to be kept in mind when subtracting months from dates. For example, what date corresponds to 2 months before 2014-04-29, 2014-04-30, 2014-08-31, 2016-04-29, 2016-04-30?
*Warning: untested SQL: syntax errors are possible.* | ```
SELECT STATE_CODE, SUM(COLA) SUM_COLA, SUM(COLB) SUM_COLB
FROM TABLE_NAME
WHERE to_date(ExtractDay(sysdate) || MONTH || YEAR, 'ddMMyyyy')
BETWEEN add_months(sysdate,-12) AND add_months(sysdate,-24)
GROUP BY STATE_CODE;
``` | Filter records by year and month where year and month are columns in the table | [
"",
"sql",
"oracle",
""
] |
I am trying to populate an autocomplete select field which needs to show all users but add a flag next to those that exist in the club table for the current club.
```
Users
user_id | first_name | last_name
--------------------------------
1 | Bob | Smith
2 | Lisa | Someone
3 | Bill | Green
4 | Jane | Hill
Club
club_id | user_id
-----------------
1 | 2
2 | 1
2 | 4
```
Output I need when I am looking for all users in the context of club "2"
```
1 | Bob | Smith | TRUE
2 | Lisa | Someone |
3 | Bill | Green |
4 | Jane | Hill | TRUE
```
I don't know why this is bending my mind so much...
Tim | You can do this with a `left outer join`:
```
select u.user_id, u.first_name, u.last_name,
(c.club_id = 2) as flag
from users u left join
club c
on u.user_id = c.user_id;
```
Note that the `flag` gets a value of `0` (false) or `1` (true). If you want some other values for the flag, then you will need to use a `case` statement.
EDIT:
If you simply want the flag for each user, then the easiest way is:
```
select u.*,
exists (select 1 from club c where u.user_id = c.user_id and c.club_id = 2) as flag
from users u;
```
Once again, this produces a 0/1 flag. If you want a different value, then it needs to go into a `case`.
Alternatively, you could use:
```
select u.user_id, u.first_name, u.last_name,
(c.user_id is not null) as flag
from users u left join
club c
on u.user_id = c.user_id and c.club_id = 2
``` | Just to be clear about your problem statement, I created the tables and inserted the data -
```
create table users (user_id bigint not null, first_name varchar(100), last_name varchar(100));
create table club (club_id bigint not null, user_id bigint not null);
insert into users values (1, 'Bob','Smith');
insert into users values (2, 'Lisa','Someone');
insert into users values (3, 'Bill','Green');
insert into users values (4, 'Jane','Hill');
insert into club values (1, 2);
insert into club values (2, 1);
insert into club values (2, 4);
```
And here is the query that I ran -
```
select users.user_id, users.first_name, users.last_name,
case when club.club_id = 2 then 'TRUE' end as flag
from users left join club on users.user_id = club.user_id;
```
And here's the output -
```
1 Bob Smith TRUE
2 Lisa Someone NULL
3 Bill Green NULL
4 Jane Hill TRUE
``` | MySQL output all records from table but add flag if value present in another | [
"",
"mysql",
"sql",
""
] |
I've been given a large list (~50,000) of User IDs in a CSV file, and I have to query our MSSql 2008R2 database to find details of all those users (email address, etc). How can I do this, given that the source of the IDs is not in a table in order to do a join?
I have tried pasting the entire list into the query editor and inserting them into a temporary table to join onto, but quickly ran into the 1000-row limit in the `INSERT INTO` syntax.
Is there a better way to do this? The only option I can think of `is SELECT * FROM User WHERE UserId IN (..., ..., ...` which seems like it would be horribly inefficient. | If you have access to copy the file directly to the SQL server, use bulk copy.
Borrowing some excellent explanations from <http://blog.sqlauthority.com/2008/02/06/sql-server-import-csv-file-into-sql-server-using-bulk-insert-load-comma-delimited-file-into-sql-server/>
```
BULK
INSERT CSVTest
FROM 'c:\csvtest.txt'
WITH
(
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)
GO
--Check the content of the table.
SELECT *
FROM CSVTest
GO
--Drop the table to clean up database.
DROP TABLE CSVTest
GO
``` | This is too long for a comment.
Use the Import Wizard and insert them into a "temporary" table. I'm putting "temporary" in quotes, because it doesn't have be in `tempdb`.
50,000 rows is a bit long to insert them one at a time. For small sets of data, I would open the CSV file in Excel and create a separate `insert` statement for each one:
```
insert into tempids(...) select X, Y, Z;
```
where `X` and so on are values from cells. Then I'd create the table and copy these `insert` statements into SSMS studio and run them. | How to use IDs from another source (CSV file) in a query? | [
"",
"sql",
"sql-server",
""
] |
I have a table in SQL Server 2012 which has columns for two countries, let's call them CountryA and CountryB.
```
CREATE TABLE dbo.AgreementParticipants
(
AgreementParticipantsID INT NOT NULL PRIMARY KEY IDENTITY,
CountryA CHAR(3) NOT NULL FOREIGN KEY REFERENCES dbo.Country (CountryCode),
CountryB CHAR(3) NOT NULL FOREIGN KEY REFERENCES dbo.Country (CountryCode)
);
```
Note: the table has been simplified for the example, however the important thing is that is always defines a bilateral relationship between two entities. It just so happens that in this case it's two countries.
*Typical data*:
```
1 AUS USA
2 USA NZL
```
*Business rules*:
1. There will always be exactly two counties.
2. The two countries can be in either order. There is no significance to position A or B.
3. Each combination of two countries must be unique to the table. Therefore, AUS USA is considered the same as USA AUS.
4. The two countries will never be the same.
**The question**:
What is the most efficient way to enforce the uniqueness constraint?
Currently, I've considered using a trigger or a convoluted check constraint, but both solutions feel inelegant so I'd like some input from the community. | You can do this with two conditions. The first is a unique index (or constraint):
```
create unique index AgreementParticipants_CountryA_CountryB on AgreementParticipants(CountryA, CountryB)
```
The second is a condition that `CountryA` is less than `CountryB`:
```
check (CountryA < CountryB)
```
If the countries could be the same, then the condition would be `<=`.
One disadvantage of this approach is that, on insert, `CountryA` has to be less than `CountryB` (alphabetically first). Otherwise, this generates an error.
An alternative approach uses computed columns and a unique index:
```
alter table AgreementParticipants
add Country1 as (case when CountryA < CountryB then CountryA else CountryB end);
alter table AgreementParticipants
add Country2 as (case when CountryA < CountryB then CountryB else CountryA end);
create unique index AgreementParticipants_Country1_Country2 on AgreementParticipants(Country1, Country2);
```
The advantage of this approach is that the countries can be inserted into the table in either order. | Constraints like:
`CHECK ( CountryA < CountryB )`
`UNIQUE ( CountryA, CountryB )`
is one way to do it
Another way is to add computed columns like:
`CREATE TABLE t2 (CountryA ..., CountryB ...
,least_country as LEAST( CountryA, CountryB )
,greatest_country as GREATEST( CountryA, CountryB ) )`
and then put a unique constraint on the new columns. Not sure whether SQLServer supports LEAST, but it is easy to create one if it does not. | Efficient way to CHECK UNIQUE on two columns? | [
"",
"sql",
"sql-server",
""
] |
i have been trying to use this particular query to find the top three most used musical keys in songs and show all the songs made using those musical keys so far the problem is that i'm using in operator with a subquery and it doesn't work!!
i have read that instead of in using join is preferable but since i haven't used any joins i am not able to use that with the query!! plaeae help!!!
```
SELECT `Key_Name`,`Song_Title`
FROM `musicalkey_record`,`musical_keys`,`record`
WHERE `record`.`Record_ID`=`musicalkey_record`.`Record_ID`
AND `musical_keys`.`Key_ID`=`musicalkey_record`.`Key_ID`
AND `Key_Name` IN (SELECT `Key_Name` FROM `musicalkey_record`,`musical_keys`,`record`
WHERE `record`.`Record_ID`=`musicalkey_record`.`Record_ID`
AND `musical_keys`.`Key_ID`=`musicalkey_record`.`Key_ID` GROUP BY `Key_Name` ORDER BY
COUNT(`Song_Title`) DESC LIMIT 3) ORDER BY `Key_Name`;
```
query with joins but without subquery:
```
SELECT `Key_Name`,`Song_Title` FROM `musical_keys` INNER JOIN `musicalkey_record` ON
`musical_keys`.`Key_ID`=`musicalkey_record`.`Key_ID`
INNER JOIN `record` ON `record`.`Record_ID`=`musicalkey_record`.`Record_ID` AND `
Key_Name` IN ('4F','Circle of fifths','C-Major') ORDER BY `Key_Name`;
``` | I may be wrong, but it seems all those joins are not necessary. You want to count song records per musical key. So join musical\_keys with musicalkey\_record and count. To get the song names you would have to join with record, too, and use wm\_concat to get the song names in one string.
```
SELECT *
FROM
(
SELECT mk.Key_Name, GROUP_CONCAT(r.Song_Title) as Song_Titles
FROM musical_keys mk
LEFT JOIN musicalkey_record mkr ON mkr.Key_ID = mk.Key_ID
LEFT JOIN record r ON r.Record_ID = mkr.Record_ID
GROUP BY mk.Key_Name
ORDER BY COUNT(*) DESC
LIMIT 3
) dummy
ORDER BY Key_Name;
```
EDIT: If you want to show all equally ranking records, i.e. at least three, but more if record four or more have the same count as record three, then you would have to get the top three, look up the third place and then select again to get all records with at least that count.
```
SELECT mk.Key_Name, GROUP_CONCAT(r.Song_Title) as Song_Titles
FROM musical_keys mk
LEFT JOIN musicalkey_record mkr ON mkr.Key_ID = mk.Key_ID
LEFT JOIN record r ON r.Record_ID = mkr.Record_ID
GROUP BY mk.Key_Name
HAVING COUNT(*) >=
(
SELECT MIN(cnt)
FROM
(
SELECT COUNT(*) as cnt
FROM musical_keys mk
LEFT JOIN musicalkey_record mkr ON mkr.Key_ID = mk.Key_ID
GROUP BY mk.Key_Name
ORDER BY COUNT(*) DESC
LIMIT 3
) dummy
)
ORDER BY Key_Name;
```
I suppose that the Key\_Name is unique in musical\_keys? Then you can even remove musical\_keys from the inner select altogether and only select from musicalkey\_record grouping by mkr.Key\_ID instead of mk.Key\_Name. Thus the query is even shorter. | This is a simplification of Barmar's approach, reducing the number of joins:
```
SELECT mk.Key_Name, Song_Title
FROM musicalkey_record mr JOIN
musical_keys mk
ON mk.Key_ID = mr.Key_ID JOIN
record r
ON r.Record_ID = mr.Record_ID JOIN
(SELECT Key_ID
FROM musicalkey_record mr
GROUP BY Key_ID
ORDER BY COUNT(*) DESC
LIMIT 3
) top3
ON mr.Key_ID = top3.Key_ID
ORDER BY mk.Key_Name;
``` | using in operator with subquery | [
"",
"mysql",
"sql",
""
] |
I am attempting to use a sub query to query our order database and return 3 columns for example:
```
Date Orders Replacements
09-MAY-14 100 5
... ... ...
```
Each order that is created can be given a reason, which basically means that it is a replacement product i.e. orders without a reason are new orders and orders with a reason are replacement orders.
I am using the below query in an attempt to get this information, but I'm getting lots of error messages, and each time I think I've fixed one I create another 10, so assume I completely have the wrong idea here.
```
SELECT Orders.EntryDate AS "Date", COUNT(Orders.OrderNo) AS "Orders",
(SELECT COUNT(Orders.OrderNo) AS "Replacements"
FROM Orders
WHERE Orders.Reason IS NOT NULL
AND Orders.EntryDate = '09-MAY-2014'
AND Orders.CustomerNo = 'A001'
GROUP BY Orders.EntryDate
)
FROM Orders
WHERE Orders.Reason IS NULL
AND Orders.EntryDate = '09-MAY-2014'
AND Orders.CustomerNo = 'A001'
GROUP BY Orders.EntryDate
;
``` | You could could sum a `case` expression instead of having a another subquery with another `where` clause:
```
SELECT Orders.EntryDate AS "Date",
SUM (CASE WHEN Orders.Reason IS NULL THEN 1 ELSE 0 END) AS "Orders",
SUM (CASE WHEN Orders.Reason IS NOT NULL THEN 1 ELSE 0 END) AS "Replacements"
FROM Orders
WHERE Orders.EntryDate = '09-MAY-2014'
AND Orders.CustomerNo = 'A001'
GROUP BY Orders.EntryDate
``` | Why the sub query use a case!
```
SELECT Orders.EntryDate AS "Date", COUNT(Orders.OrderNo) AS "Orders",
sum(CASE WHEN Orders.reason is null then 1 else 0 end) as "Replacements"
FROM Orders
WHERE Orders.Reason IS NULL
AND Orders.EntryDate = '09-MAY-2014'
AND Orders.CustomerNo = 'A001'
GROUP BY Orders.EntryDate
```
The subquery has to execute each time, since you need to evaluate each record the case can do that for you and then sum the results. If you need to get a count of -non replacement orders then just do a different case instead of a count. | How to use a SQL sub query? | [
"",
"sql",
""
] |
I've been doing quite a bit of MySql lately for uni, and i cant seem to figure out how to get a field from a table twice in the same statement.
My database is this:
```
drop database if exists AIRLINE;
create database AIRLINE;
use AIRLINE;
CREATE TABLE AIRCRAFT
(
AircraftNo INT(20) NOT NULL,
AircraftType VARCHAR(100) NOT NULL,
FuelBurn VARCHAR(100) NOT NULL,
Airspeed VARCHAR(100) NULL,
LastInspection DATE NULL,
TotalFlyingTime INT(50) NOT NULL,
TotalTimeLeftEngine INT(50) NULL,
TotalTimeRightEngine INT(50) NULL,
PRIMARY KEY (AircraftNo)
);
CREATE TABLE PILOT
(
PilotCode INT(20) NOT NULL,
LastName VARCHAR(100) NOT NULL,
FirstName VARCHAR(100) NOT NULL,
MiddleInitial VARCHAR(50) NULL,
HiredDate DATE NULL,
BasePay VARCHAR(50) NULL,
Dependents VARCHAR(100) NULL,
License INT(50) NOT NULL,
TotalHours INT(50) NOT NULL,
PRIMARY KEY (PilotCode)
);
CREATE TABLE CUSTOMER
(
CustomerNo INT(20) NOT NULL,
Name VARCHAR(100) NOT NULL,
Contact INT(50) NOT NULL,
Phone INT(50) NOT NULL,
Street VARCHAR(100) NULL,
Suburb VARCHAR(100) NULL,
State VARCHAR(100) NULL,
Postcode INT(20) NULL,
Balance INT(50) NULL,
PRIMARY KEY (CustomerNo)
);
CREATE TABLE CHARTER
(
TripTicket INT(50) NOT NULL AUTO_INCREMENT,
CharterDate DATE NOT NULL,
PilotCode INT(20) NOT NULL,
CopilotCode INT(20) NULL,
AircraftNo INT(20) NOT NULL,
Destination VARCHAR(100) NOT NULL,
Distance INT(20) NULL,
HoursFlow INT(20) NULL,
HoursWating INT(20) NULL,
Fuel INT(20) NULL,
Oil INT(20) NULL,
CustomerNo INT(20) NOT NULL,
PRIMARY KEY (TripTicket),
FOREIGN KEY(PilotCode) REFERENCES PILOT(PilotCode),
FOREIGN KEY(CopilotCode) REFERENCES PILOT(PilotCode),
FOREIGN KEY(AircraftNo) REFERENCES AIRCRAFT(AircraftNo),
FOREIGN KEY(CustomerNo) REFERENCES CUSTOMER(CustomerNo)
);
```
My goal is to list the charterdate, destination, customer details (name, customerNo, address, phone), and pilot names (firstname, middleinitial, lastname) of all charters.
I have managed to get everything, but only with one pilot. I need to list both pilot names however.
I have googled my problem, but i cant seem to find anything.
If someone could please point me in the right direction, i would be hugely grateful.
Thanks
Cheers
Corey | You just need to `JOIN` the table twice with different aliases.
Something like:
```
SELECT p1.lastname, p2.lastname, /* other fields */
FROM CHARTER c
JOIN PILOT p1 ON p1.PilotCode = c.PilotCode
JOIN PILOT p2 on p2.PilotCode = c.CoPilotCode
``` | Give alias name as
```
SELECT a.columname1 AS 1, a.columname1 AS 2
FROM tablename a
``` | How to select column twice from the same mysql table? | [
"",
"mysql",
"sql",
""
] |
I need help crafting an advanced Postgres query. I am trying to find sentences with two words adjacent to each other, using Postgres directly, not some command language extension. My tables are:
```
TABLE word (spelling text, wordid serial)
TABLE sentence (sentenceid serial)
TABLE item (sentenceid integer, position smallint, wordid integer)
```
I have a simple query to find sentences with a single word:
```
SELECT DISTINCT sentence.sentenceid
FROM item,word,sentence
WHERE word.spelling = 'word1'
AND item.wordid = word.wordid
AND sentence.sentenceid = item.sentenceid
```
I want to filter the results of that query in turn by some other word (*word2*) whose corresponding item has an **item.sentenceid** equal to the current query result's (*item* or *sentence*)'s *sentenceid* and where **item.position** is equal to the current query result's **item.position + 1**. How can I refine my query to achieve this goal and in a performant manner? | Simpler solution, but only gives results, when there are no gaps in `item.position`s:
```
SELECT DISTINCT sentence.sentenceid
FROM sentence
JOIN item ON sentence.sentenceid = item.sentenceid
JOIN word ON item.wordid = word.wordid
JOIN item AS next_item ON sentence.sentenceid = next_item.sentenceid
AND next_item.position = item.position + 1
JOIN word AS next_word ON next_item.wordid = next_word.wordid
WHERE word.spelling = 'word1'
AND next_word.spelling = 'word2'
```
More general solution, using [window functions](http://www.postgresql.org/docs/9.1/static/tutorial-window.html):
```
SELECT DISTINCT sentenceid
FROM (SELECT sentence.sentenceid,
word.spelling,
lead(word.spelling) OVER (PARTITION BY sentence.sentenceid
ORDER BY item.position)
FROM sentence
JOIN item ON sentence.sentenceid = item.sentenceid
JOIN word ON item.wordid = word.wordid) AS pairs
WHERE spelling = 'word1'
AND lead = 'word2'
```
**Edit**: Also general solution (gaps allowed), but with joins only:
```
SELECT DISTINCT sentence.sentenceid
FROM sentence
JOIN item ON sentence.sentenceid = item.sentenceid
JOIN word ON item.wordid = word.wordid
JOIN item AS next_item ON sentence.sentenceid = next_item.sentenceid
AND next_item.position > item.position
JOIN word AS next_word ON next_item.wordid = next_word.wordid
LEFT JOIN item AS mediate_word ON sentence.sentenceid = mediate_word.sentenceid
AND mediate_word.position > item.position
AND mediate_word.position < next_item.position
WHERE mediate_word.wordid IS NULL
AND word.spelling = 'word1'
AND next_word.spelling = 'word2'
``` | I think this will match your requirements, sorry but i did not remember right now how to write it without using join clauses. Basicly i included a self join to the items and words table to get the next item on sentence for each item. If the query planner does not like much my nested select you can try to left join the words table too.
```
SELECT distinct sentence.sentenceid
FROM item inner join word
on item.wordid = word.wordid
inner join sentence
on sentence.sentenceid = item.sentenceid
left join (select sentence.sentenceid,
item.position,
word.spelling from subsequent_item
inner join subsequent_word
on item.wordid = word.wordid) subsequent
on subsequent.sentenceid = item.sentenceid
and subsequent.position = item.position +1
where word.spelling = 'word1' and subsequent.spelling = 'word2';
``` | Find sentences with two words adjacent to each other in Pg | [
"",
"sql",
"postgresql",
"full-text-search",
""
] |
I'm trying to create a SQL query that will not return rows that have the same ID. I would also like to specify a primary row so that, in the event two rows have the same ID, the primary row will be returned. If no primary row is specified I would like to return the first row.
Here is an example of the database I would like to query.
```
+----+---------+-------+
| id | primary | label |
+----+---------+-------+
| 1 | Y | A |
| 1 | | B |
| 2 | | C |
| 2 | | D |
| 3 | | E |
+----+---------+-------+
```
Here is an example of the result I am trying to achieve
```
+----+---------+-------+
| id | primary | label |
+----+---------+-------+
| 1 | Y | A |
| 2 | | C |
| 3 | | E |
+----+---------+-------+
```
I've been trying to use select distinct but I'm very unsure as to the direction to pursue to solve this problem. Any help is greatly appreciated. Thank you! | Subqueries would be more appropriate than DISTINCT in your case.
Try the below. Here is a demonstration of it getting your desired result: <http://sqlfiddle.com/#!2/97fdd3/1/0>
By the way, when there is no "primary" for the ID, this will choose the lowest label value for that ID. This is as others have stated more reliable than the 'order in the database'.
```
select *
from tbl t
where t.label = (select x.label
from tbl x
where x.primary = 'Y'
and x.id = t.id)
or (not exists
(select 1
from tbl x
where x.primary = 'Y'
and x.id = t.id) and
t.label = (select min(x.label) from tbl x where x.id = t.id))
``` | I can see you already got an answer, but you could also use a regular `LEFT JOIN`;
```
SELECT * FROM mytable a
LEFT JOIN mytable b
ON a.id = b.id AND (
a.label>b.label AND a.primary IS NULL AND b.primary IS NULL OR
a.primary IS NULL AND b.primary='Y')
WHERE b.id IS NULL
```
[An SQLfiddle to test with](http://sqlfiddle.com/#!2/4cbc9f/2). | Removing duplicates from SQL query | [
"",
"mysql",
"sql",
""
] |
I am trying to figure out this without any success i have tried going through several posts but cannot come to a solution. Situation is like this : ( There are no foreign key constraints )`Table A ID | VAL Table B ID|VAL|TEMP RESULT REQUIRED
1 | A 1| A | 2 A
1 | B 1| A | 2 C
1 | C 1| B | 1 D
1 | D 1| C | 2 E
1 | E 1| D | 2 F
1 | F 1| G | 6 H
1 | H`
When i run | I think this is what you are looking for:
```
select distinct a.val
from a
left outer join b on (a.val = b.val)
where
(b.temp > 1 or b.val is null)
```
You want to do the test on B.TEMP after doing the outer join. In the where clause, you are testing for two things. Firstly, you a checking that the value of TEMP is greater than 1. This is the condition set forward in the question. The second condition (`b.val is null`) covers those rows from table A that don't have a corresponding row in table B. For example, rows 'E', 'F' and 'G' in table A don't match to anything in table B, so all the columns of B will be null after the outer join. you might want to look at this link for more information on outer joins: [What is the difference between "INNER JOIN" and "OUTER JOIN"?](https://stackoverflow.com/questions/38549/difference-between-inner-and-outer-join)
Howveer, I have noticed that the rows in table B don't need to be unique. You have two rows where VAL= 'A'. What would happen if the TEMP column had different values where one met the condition and the other didn't.
Another option for getting the result might just be to use `NOT IN` or `NOT EXISTS`. An example might be:
```
select * from a
where a.val not in (
select val
from b
where temp < 2
);
``` | If you want to exclude results from the second table, then don't use a `left outer join`. Just use an `inner join`:
```
SELECT DISTINCT A.VAL, B.TEMP
FROM A INNER JOIN
B
ON A.VAL = B.VAL AND B.TEMP > 1;
```
Or, in your case, you might want `B.TEMP < 2`. | Sql : left join exclude values based on another table | [
"",
"sql",
"sql-server",
""
] |
I have a table named `tuition`
I want to retrieve all the students who study `111` and who does not study `333`
This is what I can think of:
<http://www.sqlfiddle.com/#!2/f6411/3>
```
stud_id | subject_id
--------------------
1 111
1 222
2 222
2 333
3 111
3 222
3 333
4 111
4 222
```
**Output:**
```
stud_id
-------
1
4
``` | Three alternatives:
1. Using `HAVING` clause and `WHERE` clause:
```
SELECT *
FROM tution
WHERE subject_id = 111 OR subject_id=333
GROUP BY stud_id
HAVING COUNT(DISTINCT subject_id)=1 AND subject_id<>333
```
Result in [**SQL Fiddle**](http://www.sqlfiddle.com/#!2/df178/1).
2. Using `HAVING` clause without `WHERE` clause:
```
SELECT *
FROM tution
GROUP BY stud_id
HAVING COUNT(DISTINCT subject_id)=2 AND subject_id =111 AND subject_id<>333
```
Result in [**SQL Fiddle**](http://www.sqlfiddle.com/#!2/86252/1).
3. Using `IN`:
```
SELECT *
FROM tution
WHERE subject_id=111
AND stud_id NOT IN (SELECT stud_id FROM tution WHERE subject_id= 333)
```
Result in [**SQL Fiddle**](http://www.sqlfiddle.com/#!2/f6411/8).
Result:
```
STUD_ID SUBJECT_ID
1 111
4 111
``` | ```
select stud_id from tution
where stud_id not in (select stud_id from tution t
where t.subject_id = 333)
and subject_id = 111
```
[Fiddle](http://www.sqlfiddle.com/#!2/f6411/34) | Retrieve records satisfying a condition and not satisfying another condition | [
"",
"mysql",
"sql",
""
] |
I have the following query:
```
SELECT DISTINCT
e.id,
folder,
subject,
in_reply_to,
message_id,
"references",
e.updated_at,
(
select count(*)
from emails
where
(
select "references"[1]
from emails
where message_id = e.message_id
) = ANY ("references")
or message_id =
(
select "references"[1]
from emails
where message_id = e.message_id
)
)
FROM "emails" e
INNER JOIN "email_participants"
ON ("email_participants"."email_id" = e."id")
WHERE (("user_id" = 220)
AND ("folder" = 'INBOX'))
ORDER BY e."updated_at" DESC
LIMIT 10 OFFSET 0;
```
[Here](http://explain.depesz.com/s/tvcP) is the [explain analyze](http://explain.depesz.com/s/tvcP) output of the above query.
The query peformed fine until I added the count subquery below:
```
(
select count(*)
from emails
where
(
select "references"[1]
from emails
where message_id = e.message_id
) = ANY ("references")
or message_id =
(
select "references"[1]
from emails
where message_id = e.message_id
)
)
```
In fact I have tried simpler subqueries and it seems to be the aggregate function itself that is taking the time.
Is then an alternative way that I could append the count subquery onto each result? Should I update the results after the initial query has run for example?
Here is a [pastebin](http://pastebin.com/nzwCGxD2) that will create the table and also run the badly performing query at the end to display what the output should be. | Expanding on Paul Guyot's answer you could move the subquery into a derived table, which should perform faster because it fetches the message counts in one scan (plus a join) as opposed to 1 scan per row.
```
SELECT DISTINCT
e.id,
e.folder,
e.subject,
in_reply_to,
e.message_id,
e."references",
e.updated_at,
t1.message_count
FROM "emails" e
INNER JOIN "email_participants"
ON ("email_participants"."email_id" = e."id")
INNER JOIN (
SELECT COUNT(e2.id) message_count, e.message_id
FROM emails e
LEFT JOIN emails e2 ON (ARRAY[e."references"[1]] <@ e2."references"
OR e2.message_id = e."references"[1])
GROUP BY e.message_id
) t1 ON t1.message_id = e.message_id
WHERE (("user_id" = 220)
AND ("folder" = 'INBOX'))
ORDER BY e."updated_at" DESC
LIMIT 10 OFFSET 0;
```
Fiddle using pastebin data - <http://www.sqlfiddle.com/#!15/c6298/7>
Below are the query plans postgres produces for getting count in a correlated subquery vs getting count by joining a derived table. I used one of my own tables but I think the results should be similar.
**Correlated Subquery**
```
"Limit (cost=0.00..1123641.81 rows=1000 width=8) (actual time=11.237..5395.237 rows=1000 loops=1)"
" -> Seq Scan on visit v (cost=0.00..44996236.24 rows=40045 width=8) (actual time=11.236..5395.014 rows=1000 loops=1)"
" SubPlan 1"
" -> Aggregate (cost=1123.61..1123.62 rows=1 width=0) (actual time=5.393..5.393 rows=1 loops=1000)"
" -> Seq Scan on visit v2 (cost=0.00..1073.56 rows=20018 width=0) (actual time=0.002..4.280 rows=21393 loops=1000)"
" Filter: (company_id = v.company_id)"
" Rows Removed by Filter: 18653"
"Total runtime: 5395.369 ms"
```
**Joining a Derived Table**
```
"Limit (cost=1173.74..1211.81 rows=1000 width=12) (actual time=21.819..22.629 rows=1000 loops=1)"
" -> Hash Join (cost=1173.74..2697.72 rows=40036 width=12) (actual time=21.817..22.465 rows=1000 loops=1)"
" Hash Cond: (v.company_id = visit.company_id)"
" -> Seq Scan on visit v (cost=0.00..973.45 rows=40045 width=8) (actual time=0.010..0.198 rows=1000 loops=1)"
" -> Hash (cost=1173.71..1173.71 rows=2 width=12) (actual time=21.787..21.787 rows=2 loops=1)"
" Buckets: 1024 Batches: 1 Memory Usage: 1kB"
" -> HashAggregate (cost=1173.67..1173.69 rows=2 width=4) (actual time=21.783..21.784 rows=3 loops=1)"
" -> Seq Scan on visit (cost=0.00..973.45 rows=40045 width=4) (actual time=0.003..6.695 rows=40046 loops=1)"
"Total runtime: 22.806 ms"
``` | From what I understand of the semantics of your query, you can simplify:
```
select count(*)
from emails
where
(
select "references"[1]
from emails
where message_id = e.message_id
) = ANY ("references")
or message_id =
(
select "references"[1]
from emails
where message_id = e.message_id
)
```
to:
```
select count(*)
from emails
where
e."references"[1] = ANY ("references") OR message_id = e."references"[1]
```
Indeed, message\_id is not necessarily unique, but if, for a given value of message\_id, you do have distinct rows, your query will fail.
This simplification does not, however, change the cost of the query significantly. Indeed, the issue here is that you need two full scans of table emails to perform the query (as well as an index scan on emails\_message\_id\_index). You could save one full scan by using an index on the references array.
You would create such an index with:
```
CREATE INDEX emails_references_index ON emails USING GIN ("references");
```
The index alone does help the initial query significantly: provided that there are up-to-date statistics, as with a sufficiently large number of rows, PostgreSQL will perform an index scan. Yet, you should alter the subquery as follows, to help the planner perform a bitmap index scan on this array index:
```
select count(*)
from emails
where
ARRAY[e."references"[1]] <@ "references"
OR message_id = e."references"[1]
```
The final query would read:
```
SELECT DISTINCT
e.id,
folder,
subject,
in_reply_to,
message_id,
"references",
e.updated_at,
(
select count(*)
from emails
where
ARRAY[e."references"[1]] <@ "references"
OR message_id = e."references"[1]
)
FROM "emails" e
INNER JOIN "email_participants"
ON ("email_participants"."email_id" = e."id")
WHERE (("user_id" = 220)
AND ("folder" = 'INBOX'))
ORDER BY e."updated_at" DESC
LIMIT 10 OFFSET 0;
```
To illustrate the expected gains, some tests were conducted in a dummy environment:
* with **10,000** rows in table emails (and corresponding rows in table email\_participants), initial query runs in 787ms, with the index scan this drops to 399ms and the proposed query runs in 12ms;
* with **100,000** rows initial query runs in 9,200ms, with the index scan this drops to 4,251ms and the proposed query runs in 637ms. | alternative to SQL count subquery | [
"",
"sql",
"postgresql",
""
] |
I tried this query but I can't get it to work:
It says that there's a syntax error near EXISTS.
```
SELECT *
FROM Customers
WHERE CustomerID EXIST IN (SELECT *, CustomerID FROM Orders);
```
Thanks in advance. | the error is right. You even wrote `Exists` in your question but in the example code you wrote `exist` with no `s` on the end. See [here](http://www.techonthenet.com/sql/exists.php) for the proper syntax
You need to correlate the outer query with the sub query in the `exists`. It doesn't matter what columns you select because by rule they are not allowed to be evaluated (i.e. `select *` is fine)
```
SELECT *
FROM Customers C
WHERE EXISTS (SELECT * FROM Orders where Orders.CustomerID = C.CustomerID);
``` | Try something like this:
```
SELECT * FROM Customers WHERE CustomerID IN (SELECT CustomerID FROM Orders);
``` | EXISTS query don't work. Error in Syntax | [
"",
"sql",
"exists",
""
] |
I have what seems like a very silly question to me. I have a query that looks something like:
```
SELECT id FROM myTable WHERE valueCol BETWEEN :x and :y;
```
This works great when `:x <= :y` BUT, when `:x > :y` it doesn't return the rows I want! For this case I have to manually reverse the variables to get it to work correctly.
Is there a way to write a between clause where the order of the variables doesn't matter?
PS> I included SQL since I am pretty sure this is just a general sql issue. | Yes that's easy:
```
SELECT id
FROM myTable
WHERE valueCol BETWEEN LEAST(:x,:y) and GREATEST(:x,:y);
``` | You could do the check yourself and swap the values, or, you could do something like this and let Oracle figure it out:
```
BETWEEN LEAST(:x,:y) AND GREATEST(:x,:y)
``` | Between clause - do I have to reorder the parameters? | [
"",
"sql",
"oracle",
"between",
""
] |
How can I find maximum value on multiple columns.
This is what I have so far.
```
With Temp AS (
SELECT P.ID AS 'Product_ID',
P.ProductCode AS 'Product_Code',
P.Name AS 'Product_Name',
P.SellPrice AS 'SellPrice',
P.SellPrice+(P.SellPrice*TVA/100) AS 'PricePerUnit',
P.TVA AS 'TVA',
P.Discount AS 'Discount_Product',
0 AS 'Discount_Code',
0 AS 'Discount_Newsletter',
V.ID AS 'Variant_ID',
V.Nume AS 'Variant_Name',
V.Stock-V.Reserved AS 'Quantity_MAX',
T.Quantity AS 'Quantity',
I.ImageName AS 'Image',
0 AS 'Is_Kit'
FROM TemporaryShoppingCart T
INNER JOIN ProductVariant V ON V.ID=T.Variant_ID
INNER JOIN Product P ON P.ID=V.ProductID
LEFT JOIN ProductImage I ON I.ProductID=P.ID AND DefaultImage=1
WHERE T.ID=@ID AND T.Variant_ID!=0
) SELECT t.* ,MAX(MAXValue) FROM (SELECT (T.Discount_Product) AS 'MAXValue'
UNION ALL
SELECT (T.Discount_Code)
UNION ALL
SELECT (T.Discount_Newsletter)) as 'maxval' //error
FROM Temp T
```
This code is giving me the error: *Incorrect syntax near 'maxval'.* | Are you simply looking for GREATEST?
```
SELECT
t.*,
GREATEST(T.Discount_Product, T.Discount_Code, T.Discount_Newsletter) as 'maxval'
FROM Temp T;
```
However GREATEST Returns NULL when a value is NULL, so you might want to care about this, too. For instance:
```
SELECT
t.*,
GREATEST
(
coalesce(T.Discount_Product,0),
coalesce(T.Discount_Code, 0),
coalesce(T.Discount_Newsletter, 0)
) as 'maxval'
FROM Temp T;
```
EDIT: In case GREATEST is not available in your dbms you can use a case expression.
```
SELECT
t.*,
CASE
WHEN coalesce(T.Discount_Product, 0) > coalesce(T.Discount_Code, 0)
AND coalesce(T.Discount_Product, 0) > coalesce(T.Discount_Newsletter, 0)
THEN coalesce(T.Discount_Product, 0)
WHEN coalesce(T.Discount_Code, 0) > coalesce(T.Discount_Product, 0)
AND coalesce(T.Discount_Code, 0) > coalesce(T.Discount_Newsletter, 0)
THEN coalesce(T.Discount_Code, 0)
ELSE coalesce(T.Discount_Newsletter, 0)
END
FROM Temp T;
```
EDIT: To get your own statement syntactically correct, do:
```
SELECT
t.*,
(
select MAX(Value)
FROM
(
SELECT T.Discount_Product AS Value
UNION ALL
SELECT T.Discount_Code
UNION ALL
SELECT T.Discount_Newsletter
) dummy -- T-SQL requires a name for such sub-queries
) as maxval
FROM Temp T;
``` | You probably want to have each `Select` statement to have a From clause. | Finding max value of multiple columns in Sql | [
"",
"sql",
"sql-server",
"max",
""
] |
We have application which collect huge data daily. So write operation is more, Hence my server slow down. So what we have planned use MongoDB to collect data, By using scheduler will import data to SQL.
So my problem is how can I import that much heavy data from MongoDB to SQL
Any suggestion Please. Like any tool etc. | I don't know any tools, but I'm sure they exist if you google them.
If it was me, without prior knowledge, I may export data to a flat file (.csv) and create either a stored procedure or an SSIS package to import the data into SQL.
Python may be my choice to automate the exports in chunks overnight where SQL can handle the importation and cleanup.
```
mongoexport --host yourhost --db yourdb --collection yourcollection --csv --out yourfile.csv --fields field1,field2,field3
```
Doing it this way allows you to define the structure before it hits the SSIS package.
**Another way**
Here is a good example of doing all collections. This was from another [answer](https://stackoverflow.com/questions/11255630/how-to-export-all-collection-in-mongodb).
```
out = `mongo #{DB_HOST}/#{DB_NAME} --eval "printjson(db.getCollectionNames())"`
collections = out.scan(/\".+\"/).map { |s| s.gsub('"', '') }
collections.each do |collection|
system "mongoexport --db #{DB_NAME} --collection #{collection} --host '#{DB_HOST}' --out #{collection}_dump"
end
``` | We created [MongoSluice](http://mongosluice.com) for this specific reason.
Our application interrogates a MongoDB collection and creates a full, deep schema. It then streams data and meta data to any RDBMS system (Oracle, MySQL, Postgres, HP Vertica...).
What you end up with is a representation of your NoSQL as SQL. A big use case for this is to get unstructured data into analytical databases. BI platforms, particularly. | How can import Large data from MongoDB to SQL Server Like Schedulers | [
"",
"sql",
"sql-server",
"mongodb",
""
] |
I have two tables like this.
```
A B
1 12
2 13
3 12
4 13
5 15
B C
12 APPLE
13 ORANGE
14 MANGO
15 BANANA
```
I need output as below...
```
count(A) B C
2 12 APPLE
2 13 ORANGE
0 14 MANGO
1 15 BANANA
```
I have written the query using joins but I am stuck at displaying the count as zero in case of empty value. | Use a `left join` to get the values of `table2` even if there are no records for them in `table1`
```
select T2.B, T2.C, count(T1.A)
from table2 T2
left join table1 T1 on T1.B = T2.B
group by T2.B, T2.C
``` | Try this:
```
SELECT COUNT(T1.A) as Cnt,T2.B,T2.C
FROM Table2 T2 LEFT JOIN
Table1 T1 ON T1.B=T2.B
GROUP BY T2.B,T2.C
```
Result:
```
CNT B C
2 12 APPLE
1 15 BANANA
0 14 MANGO
2 13 ORANGE
```
See result in [**SQL Fiddle**](http://www.sqlfiddle.com/#!3/b1846/8). | Query to count the entries | [
"",
"sql",
"sql-server",
"join",
""
] |
I want to write a SQL to count the sales of my last six months, just like the code below.
```
SELECT
MONTH (pc.createTime) AS MONTH,
SUM (partsModelSum) AS totalSum
FROM
partscontractlinkmodel AS pl
RIGHT JOIN partscontract pc ON pl.partsContractID = pc.partsContractID
AND pc.companyID = 8
AND pc.createTime BETWEEN '2013/11/01 00:00:00'
AND '2014/04/30 23:59:59'
WHERE
pl.partsModelID = 21028
GROUP BY
MONTH (pc.createTime)
ORDER BY
totalSum DESC
```
AND results is:
```
month totalSum
4 24
```
But the problem the problem arises,No sales record month does not appear in the query results, **I want there is no sales records in results and a value of 0**
like this:
```
month totalSum
4 24
3 0
2 0
1 0
12 0
11 0
```
**So,How to modify sql solve my problem ;)
thanks** | If you have some data every month, you can use conditional aggregation:
```
SELECT MONTH (pc.createTime) AS MONTH,
SUM(CASE WHEN pl.partsModelID = 21028 THEN partsModelSum END) AS totalSum
FROM partscontract pc LEFT JOIN
partscontractlinkmodel pl
ON pl.partsContractID = pc.partsContractID AND
pc.companyID = 8 AND
pc.createTime BETWEEN '2013/11/01 00:00:00' AND '2014/04/30 23:59:59'
GROUP BY
MONTH(pc.createTime)
ORDER BY totalSum DESC;
```
If this doesn't work, you need to generate the list of months using a subquery or CTE. | Get a list of month from a table or sub query. Left join the months table/query and partscontract via month(createTime) and month from table/sub-query. Left join partscontract and partscontractlinkmodel like what you did. See below for sample:
;WITH CTE\_Month
as
(
SELECT 1 as MonthN
UNION
SELECT 2 as MonthN
UNION
SELECT 3 as MonthN
UNION
SELECT 4 as MonthN
UNION
SELECT 5 as MonthN
UNION
SELECT 6 as MonthN
UNION
SELECT 7 as MonthN
UNION
SELECT 8 as MonthN
UNION
SELECT 9 as MonthN
UNION
SELECT 10 as MonthN
UNION
SELECT 11 as MonthN
UNION
SELECT 12 as MonthN
),
SELECT
N.MonthN AS MONTH,
SUM (ISNULL(partsModelSum,0)) AS totalSum
FROM
CTE\_Month M
LEFT JOIN partscontract pc ON MONTH (pc.createTime) = N.MonthN
LEFT JOIN partscontractlinkmodel AS pl
ON pl.partsContractID = pc.partsContractID
AND pc.companyID = 8
AND pc.createTime BETWEEN '2013/11/01 00:00:00'
AND '2014/04/30 23:59:59'
WHERE
pl.partsModelID = 21028
GROUP BY
N.MonthN
ORDER BY
totalSum DESC | SqlServer:Select and group by Month | [
"",
"sql",
""
] |
Is there a way to change same column name with same column type in multiple tables in one query?
something like this:
```
ALTER TABLE
(SELECT DISTINCT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE 'data_by_%_month_%'
AND TABLE_SCHEMA='db_name')
MODIFY column1 INT(20) NOT NULL;
``` | No, not with `ALTER TABLE` alone. It is expected for the `ALTER TABLE` statement to receive one table.
See [the docs](http://dev.mysql.com/doc/refman/5.1/en/alter-table.html). It doesn't expect an expression there.
You can of course write a program that creates multiple `ALTER TABLE` statements based on your `SELECT` Query. | You can do this using a stored procedure.
**Example**:
***Test table structures***:
```
drop table if exists so.tbl_so_q23631366_1;
drop table if exists so.tbl_so_q23631366_2;
create table so.tbl_so_q23631366_1( column1 varchar(10) );
create table so.tbl_so_q23631366_2( column1 text );
```
***Stored Procedure***:
```
drop procedure if exists modify_column;
delimiter //
create procedure modify_column()
begin
declare no_more_to_fetch boolean default false;
declare alter_table_string varchar(1024) default '';
declare alter_stmts_crsr cursor for
select concat( 'alter table ', table_name
, ' modify column1 INT(20) NOT NULL default 0;' )
from information_schema.tables
where table_name like 'tbl_so_q23631366%' -- 'data_by_%_month_%'
and table_schema='so'; -- 'db_name';
declare continue handler for not found
set no_more_to_fetch = true;
open alter_stmts_crsr;
Result_Set: loop
fetch alter_stmts_crsr into alter_table_string;
if( no_more_to_fetch ) then
leave Result_Set;
end if;
-- un comment following line to debug
-- select alter_table_string;
set @sql := alter_table_string;
prepare stmt from @sql;
execute stmt;
drop prepare stmt;
end loop Result_Set;
close alter_stmts_crsr;
end;
//
delimiter ;
```
***Call stored procedure***:
```
call modify_column;
```
***See modified table structures***:
```
desc tbl_so_q23631366_1; desc tbl_so_q23631366_2;
``` | ALTER columns from multiple tables in same query | [
"",
"mysql",
"sql",
""
] |
I have a table with sample data as below:
```
Name | Code
Ken Ken_A
Ken Ken_B
Tim Tim_1
Tim Tim_3
Sam Sam_Tens
Sam Sam_Tenson
```
I want to do an update query that replaces the second instance of the Code ordered by Name with the first instance, so I would end up with the below:
```
Name | Code
Ken Ken_A
Ken Ken_A
Tim Tim_1
Tim Tim_1
Sam Sam_Tens
Sam Sam_Tens
``` | Assuming that you have a column that specifies the ordering, you can use an updatable CTE with a join:
```
with toupdate as (
select t.*, row_number() over (partition by name order by id) as seqnum
from t
)
update toupdate
set code = tu2.code
from toupdate join
toupdate tu2
on toupdate.name = tu2.name and
tu2.seqnum = 1 and
toupdate.seqnum > 1;
```
If you don't have a column that identifies the ordering of the rows, then your question doesn't make sense. In SQL, tables are inherently unordered. | One option:
```
update mytable
set code = (select min(code) from mytable min_name where min_name.name = mytable.name);
``` | Update row with Top 1 value per group | [
"",
"sql",
"sql-server-2008",
"t-sql",
""
] |
I am trying to create an audit trail for actions that are performed within a web application, SQL server agent jobs and manually run queries to the database. I am trying to use triggers to catch updates, inserts and deletes on certain tables.
In the whole this process is working. Example, user performs update in web application and the trigger writes the updated data to an audit trail table I have defined, including the username of the person who performed the action. This works fine from a web application or manual query perspective, but we also have dozens of SQL Server Agent Jobs that I would like to capture which one ran specific queries. Each of the agent jobs are ran with the same username. This works fine also and inputs the username correctly into the table but I can't find which job calls this query.
My current "solution" was to find which jobs are currently running at the time of the trigger, as one of them must be the correct one. Using:
```
CREATE TABLE #xp_results
(
job_id UNIQUEIDENTIFIER NOT NULL,
last_run_date INT NOT NULL,
last_run_time INT NOT NULL,
next_run_date INT NOT NULL,
next_run_time INT NOT NULL,
next_run_schedule_id INT NOT NULL,
requested_to_run INT NOT NULL, -- BOOL
request_source INT NOT NULL,
request_source_id sysname COLLATE database_default NULL,
running INT NOT NULL, -- BOOL
current_step INT NOT NULL,
current_retry_attempt INT NOT NULL,
job_state INT NOT NULL
)
INSERT INTO #xp_results
EXECUTE master.dbo.xp_sqlagent_enum_jobs 1, 'sa'
SELECT @runningJobs = STUFF((SELECT ',' + j.name
FROM #xp_results r
INNER JOIN msdb..sysjobs j ON r.job_id = j.job_id
WHERE running = 1
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
DROP TABLE #xp_results
```
I ran a specific job to test and it seems to work, in that any OTHER job which is running will be listed in `@runningJobs`, but it doesn't record the job that runs it. I assume that by the time the trigger runs the job has finished.
Is there a way I can find out what job calls the query that kicks off the trigger?
**EDIT**: I tried changing the `SELECT` query above to get any job that ran within the past 2 mins or is currently running. The SQL query is now:
```
SELECT @runningJobs = STUFF((SELECT ',' + j.name
FROM #xp_results r
INNER JOIN msdb..sysjobs j ON r.job_id = j.job_id
WHERE (last_run_date = CAST(REPLACE(LEFT(CONVERT(VARCHAR, getdate(), 120), 10), '-', '') AS INT)
AND last_run_time > CAST(REPLACE(LEFT(CONVERT(VARCHAR,getdate(),108), 8), ':', '') AS INT) - 200)
OR running = 1
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
```
When I run a job, then run the above query while the job is running, the correct jobs are returned. But when the SSIS package is run, either via the SQL Server Agent job or manually ran in SSIS, the `@runningJobs` is not populated and just returns `NULL`.
So I am now thinking it is a problem with permissions of SSIS and `master.dbo.xp_sqlagent_enum_jobs`. Any other ideas?
**EDIT #2**: Actually don't think it is a permissions error. There is an `INSERT` statement below this code, if it IS a permissions error the `INSERT` statement does not run and therefore the audit line does not get added to the database. So, as there IS a line added to the database, just not with the `runningJobs` field populated. Strange times.
**EDIT #3**: I just want to clarify, I am searching for a solution which DOES NOT require me to go into each job and change anything. There are too many jobs to make this a feasible solution. | **WORKING CODE IS IN FIRST EDIT** - (*anothershrubery*)
Use the `app_name()` function <http://msdn.microsoft.com/en-us/library/ms189770.aspx> in your audit trigger to get the name of the app running the query.
For SQL Agent jobs, app\_name includes the job step id in the app name (if a **T-SQL** step). We do this in our audit triggers and works great. An example of the `app_name()` results when running from within an audit trigger:
> SQLAgent - TSQL JobStep (Job 0x96EB56A24786964889AB504D9A920D30 : Step
> 1)
This job can be looked up via the `job_id` column in `msdb.dbo.sysjobs_view`.
Since SSIS packages initiate the SQL connection outside of the SQL Agent job engine, those connections will have their own application name, and you need to set the application name within the connection strings of the SSIS packages. In SSIS packages, Web apps, WinForms, or any client that connects to SQL Server, you can set the value that is returned by the app\_name function by using this in your connection string :
```
"Application Name=MyAppNameGoesHere;"
```
<http://www.connectionstrings.com/use-application-name-sql-server/>
If the "Application Name" is not set within a .NET connection string, then the default value when using the `System.Data.SqlClient.SqlConnection` is ".Net SqlClient Data Provider".
Some other fields that are commonly used for auditing:
* **HOST\_NAME()**: <http://technet.microsoft.com/en-us/library/ms178598.aspx> Returns the name of the client computer that is connecting. This is helpful if you have an intranet app.
* **CONNECTIONPROPERTY('local\_net\_address')**: For getting the client IP address.
* **CONTEXT\_INFO()**: <http://technet.microsoft.com/en-us/library/ms187768.aspx> You can use this to store information for the duration of the connection/session. Context\_Info is a binary 128 byte field, so you might need to do conversions to/from strings when using it.
Here are SQL helper methods for setting/getting context info:
```
CREATE PROC dbo.usp_ContextInfo_SET
@val varchar(128)
as
begin
set nocount on;
DECLARE @c varbinary(128);
SET @c=cast(@val as varbinary(128));
SET CONTEXT_INFO @c;
end
GO
CREATE FUNCTION [dbo].[ufn_ContextInfo_Get] ()
RETURNS varchar(128)
AS
BEGIN
--context_info is binary data type, so will pad any values will CHAR(0) to the end of 128 bytes, so need to replace these with empty string.
RETURN REPLACE(CAST(CONTEXT_INFO() AS varchar(128)), CHAR(0), '')
END
```
**EDIT:**
The app\_name() is the preferred way to get the application that is involved in the query, however since you do not want to update any of the SSIS packages, then here is an updated query to get currently executing jobs using the following documented SQL Agent tables. You may have to adjust the GRANTs for SELECT in the msdb database for these tables in order for the query to succeed, or create a view using this query, and adjust the grants for that view.
* msdb.dbo.sysjobactivity <http://msdn.microsoft.com/en-us/library/ms190484.aspx>
* msdb.dbo.syssessions <http://msdn.microsoft.com/en-us/library/ms175016.aspx>
* msdb.dbo.sysjobs <http://msdn.microsoft.com/en-us/library/ms189817.aspx>
* msdb.dbo.sysjobhistory <http://msdn.microsoft.com/en-us/library/ms174997.aspx>
Query:
```
;with cteSessions as
(
--each time that SQL Agent is started, a new record is added to this table.
--The most recent session is the current session, and prior sessions can be used
--to identify the job state at the time that SQL Agent is restarted or stopped unexpectedly
select top 1 s.session_id
from msdb.dbo.syssessions s
order by s.agent_start_date desc
)
SELECT runningJobs =
STUFF(
( SELECT N', [' + j.name + N']'
FROM msdb.dbo.sysjobactivity a
inner join cteSessions s on s.session_id = a.session_id
inner join msdb.dbo.sysjobs j on a.job_id = j.job_id
left join msdb.dbo.sysjobhistory h2 on h2.instance_id = a.job_history_id
WHERE
--currently executing jobs:
h2.instance_id is null
AND a.start_execution_date is not null
AND a.stop_execution_date is null
ORDER BY j.name
FOR XML PATH(''), ROOT('root'), TYPE
).query('root').value('.', 'nvarchar(max)') --convert the xml to nvarchar(max)
, 1, 2, '') -- replace the leading comma and space with empty string.
;
```
**EDIT #2:**
Also if you are on SQL 2012 or higher, then checkout the `SSISDB.catalog.executions` view [http://msdn.microsoft.com/en-us/library/ff878089(v=sql.110).aspx](http://msdn.microsoft.com/en-us/library/ff878089%28v=sql.110%29.aspx) to get the list of currently running SSIS packages, regardless of if they were started from within a scheduled job. I have not seen an equivalent view in SQL Server versions prior to 2012. | You could try using CONTEXT\_INFO
Try adding a T-SQL step with `SET CONTEXT_INFO 'A Job'` in to your job
Then try reading that in your trigger using `sys.dm_exec_sessions`
I'm curious to see if it works - please post your findings.
[http://msdn.microsoft.com/en-us/library/ms187768(v=sql.105).aspx](http://msdn.microsoft.com/en-us/library/ms187768%28v=sql.105%29.aspx) | Get job that ran SQL query on UPDATE trigger | [
"",
"sql",
"sql-server",
"triggers",
"ssis",
"sql-server-job",
""
] |
I think the best way to describe what I am looking for is to show a table of data and what I want returned from my Query. This is a simple data table in SQL Server:
```
JobNumber TimeOfWeigh
100 01/01/2014 08:00
100 01/01/2014 09:00
100 01/01/2014 10:00
200 01/01/2014 12:00
200 01/01/2014 13:00
300 01/01/2014 15:00
300 01/01/2014 16:00
100 02/01/2014 08:00
100 02/01/2014 09:00
100 03/01/2014 10:00
```
I want a query that will group the job and return the first and last DateTime from each group. However, as you can see here there are 2 sets of the 100 Job Number. I dont want the second set joined with the first.
Instead I would like this:
```
JobNumber First Weigh Last Weigh
100 01/01/2014 08:00 01/01/2014 10:00
200 01/01/2014 12:00 01/01/2014 13:00
300 01/01/2014 15:00 01/01/2014 16:00
100 02/01/2014 08:00 03/01/2014 10:00
```
I have been struggling with this for hours. Any help would be appreciated.
EDITED
The Date & Times are all just dummy random data. The actual data has thousands of weighs within one day. I want the first and last weight of each job to determine the duration of the job so I can represent the duration on a timeline. But I want to display Job 100 twice, indicating it was paused and resumed after 200 & 300 were completed | Here's my attempt at this, using row\_number() with a partition. I've broken it into steps to hopefully make it easy to follow. If your table already has a column with integer identifiers in it, then you can omit the first CTE. Even after that, you might be able to simplify this further, but it does appear to work.
(Edited to add a flag indicating jobs with multiple ranges as requested in a comment.)
```
declare @sampleData table (JobNumber int, TimeOfWeigh datetime);
insert into @sampleData values
(100, '01/01/2014 08:00'),
(100, '01/01/2014 09:00'),
(100, '01/01/2014 10:00'),
(200, '01/01/2014 12:00'),
(200, '01/01/2014 13:00'),
(300, '01/01/2014 15:00'),
(300, '01/01/2014 16:00'),
(100, '02/01/2014 08:00'),
(100, '02/01/2014 09:00'),
(100, '03/01/2014 10:00');
-- The first CTE assigns an ordering to the records according to TimeOfWeigh,
-- producing the row numbers you gave in your example.
with JobsCTE as
(
select
row_number() over (order by TimeOfWeigh) as RowNumber,
JobNumber,
TimeOfWeigh
from @sampleData
),
-- The second CTE orders by the RowNumber we created above, but restarts the
-- ordering every time the JobNumber changes. The difference between RowNumber
-- and this new ordering will be constant within each group.
GroupsCTE as
(
select
RowNumber - row_number() over (partition by JobNumber order by RowNumber) as GroupNumber,
JobNumber,
TimeOfWeigh
from JobsCTE
),
-- Join by JobNumber alone to determine which jobs appear multiple times.
DuplicatedJobsCTE as
(
select JobNumber
from GroupsCTE
group by JobNumber
having count(distinct GroupNumber) > 1
)
-- Finally, we use GroupNumber to get the mins and maxes from contiguous ranges.
select
G.JobNumber,
min(G.TimeOfWeigh) as [First Weigh],
max(G.TimeOfWeigh) as [Last Weigh],
case when D.JobNumber is null then 0 else 1 end as [Multiple Ranges]
from
GroupsCTE G
left join DuplicatedJobsCTE D on G.JobNumber = D.JobNumber
group by
G.JobNumber,
G.GroupNumber,
D.JobNumber
order by
[First Weigh];
``` | you have to use self joins to create pseudo tables that contain the first, and last row in each set.
```
Select F.JobNumber,
f.TimeOfWeigh FirstWeigh,
l.TimeOfWeigh LastWeigh
From table f -- for first record
join table l -- for last record
on l.JobNumber = f.JobNumber
And Not exists
(Select * from table
Where JobNumber = f.JobNumber
And id = f.id-1)
And Not exists
(Select * from table
Where JobNumber = f.JobNumber
And id = l.id+1)
And Not Exists
(Select * from table
Where JobNumber <> f.JobNumber
And id Between f.Id and l.Id)
``` | Sql query to return a result set for a Timeline | [
"",
"sql",
"sql-server",
"group-by",
""
] |
Another Question for Today :)
Wrote a query that works perfectly - except I want it to show NULL/0 values as 0 - and - that isn't happening. I tried approaching this two ways:
First I used `isnull()`
```
Select isnull(Count(*),0) as Total ,
z.zname
From STable s ,
SLTable sl ,
ZTable z ,
SETable se ,
SEETable see ,
SEGTable seg
Where s.sID = sl.sID
and sl.zID = z.zID
and s.sID = se.sID
and se.etID = see.etID
and see.segID = seg.segID
and see.segID = 3
Group By z.zname
order by z.zname
```
Is doesn't seem to give me the Null/0 values
Then I tried using a sum/case approach
```
Select sum(case when see.segID <> 3 then 0 else 1 end) as Total ,
z.zname
From STable s ,
SLTable sl ,
Table z ,
SETable se ,
SEETable see ,
SEGTable seg
Where s.sID = sl.sID
and sl.zID = z.zID
and s.sID = se.sID
and se.etID = see.etID
and see.segID = seg.segID
and see.segID = 3
Group By z.zname
order by z.zname
```
And still no 0 values - so now I'm stumped :( | Well, it's unclear what you're actually trying to find. However, a big part of your problem is that you're using old-school, pre-ISO/ANSI `join` syntax. If you refactor your join to use modern `join` syntax, you'll get a query that looks somethinn (a lot, actually) like this:
```
select zName = z.zname ,
Total = count(*)
From ZTable z
join SLTable sl on sl.zID = z.zID
join STable s on s.sID = sl.sID
join SETable se on se.sID = s.sID
join SEETable see on see.etID = se.etID
and see.segID = 3
join SEGTable seg on seg.segID = see.segID
Group By z.zname
order by z.zname
```
I suspect that what you want to get is a list of *all* `zNames` and their respect counts of having `segID = 3`. Since you are using *inner* joins, you'll only ever see `zNames` that have a match. What you can do is something like this:
```
select zName = z.zname ,
Total = sum(case see.segID when 3 then 1 else 0 end)
from ZTable z
left join SLTable sl on sl.zID = z.zID
left join STable s on s.sID = sl.sID
left join SETable se on se.sID = s.sID
left join SEETable see on see.etID = se.etID
group By z.zname
order by z.zname
```
The above will return *every* row from `zTable` at least once, with `null` values for the columns of any table for which no match was found. Then we group it and count the rows where `segID` is 3. | Actually just to semi answer my own question - just realized that where - see.segID-3 - so it'll only turn out results with segID = 3 - so it cannot NOT have 3 - right?
But Im specifically looking for segIDs as 3 - just, if there is nothing there then display 0 | Null/0 Answers Not Appearing | [
"",
"sql",
"sql-server",
""
] |
I have a table it's called solr. using this below Scripti'm updating this into solr table.but here my doubt is instead of this i need to use If...Else condition.
I'm not getting any idea about this one. Kindly help me with on this.
```
UPDATE solr
SET Stock=
CASE
WHEN SUD.D_price='ABC'
OR SUD.D_price ='CDE'
AND WIS.StockID >0
THEN 'Y'
WHEN SUD.Display_price='XYZ '
OR SUD.Display_price ='PQR'
AND WIS.StockID >0
AND WI.StockName NOT LIKE '%GGR%'
THEN 'Y'
END
FROM InventoryItems WIS
JOIN solr SUD
ON WIS.ProductID=SUD.ProductId
JOIN WS_Inventory WI
ON WI.StockID=WIS.StockID
``` | You don't explain exactly what you want, but I surmise that you need an `else` clause. If you want to set the value to `'N'`, then use:
```
UPDATE solr
SET Stock = (case when SUD.D_price = 'ABC' OR SUD.D_price = 'CDE' AND WIS.StockID > 0
THEN 'Y'
WHEN SUD.Display_price='XYZ ' OR SUD.Display_price='PQR' AND WIS.StockID>0 AND WI.StockName NOT LIKE '%GGR%'
THEN 'Y'
ELSE 'N'
end)
from solr SUD join
InventoryItems WIS
on WIS.ProductID = SUD.ProductId JOIN
WS_Inventory WI
ON WI.StockID = WIS.StockID;
```
Perhaps you want:
```
ELSE stock
```
This will not change the value. You can also put conditions in the `where` clause to only update to `Y`, if that is your intention. I don't see a need for `if`. | I don't really understand your question, but I do know this... whenever you mix AND with OR in a condition, you should use parenthesis to control the order of operations.
```
CASE
WHEN (SUD.D_price='ABC' OR SUD.D_price ='CDE')
AND WIS.StockID >0
THEN 'Y'
WHEN (SUD.Display_price='XYZ' OR SUD.Display_price ='PQR')
AND WIS.StockID > 0
AND WI.StockName NOT LIKE '%GGR%'
THEN 'Y'
ELSE -- You should probably have some value here.
END
``` | Instead of Case when I need IF..Else | [
"",
"sql",
"sql-server-2008",
""
] |
These are my tables
```
create table employees
(emp_no integer not null,
emp_name char(25),
age integer,
department_id integer not null,
salary integer,
CONSTRAINT employees_pk PRIMARY KEY(emp_no),
CONSTRAINT fk_Department FOREIGN KEY(department_id)
REFERENCES Department(department_id));
insert into employees values ( 15,'sara',30 ,101 ,2000 )
insert into employees values ( 12,'maha',29 ,104 ,3000 )
insert into employees values ( 14,'ahmad',24 , 102,4400 )
insert into employees values ( 11,'ali', 27, 103, 2500)
insert into employees values ( 13,'nora', 35, 101,3500 )
create table Works
(emp_no integer not null,
hurs integer,
department_id integer not null,
CONSTRAINT Works_pk PRIMARY KEY(emp_no),
CONSTRAINT Department_fk FOREIGN KEY(department_id)
REFERENCES Department(department_id));
insert into Works values ( 11,7,103)
insert into Works values (12,9,104)
insert into Works values (13,5,101)
insert into Works values (14,10,102)
insert into Works values (15,8,101)
create table Department
(Department_id integer not null,
dep_name char(50),
CONSTRAINT Department_pk PRIMARY KEY(Department_id));
insert into Department values (101,'computer')
insert into Department values (102,'history')
insert into Department values (103,'english')
insert into Department values (104,'physics')
```
And I want to select the employee names and their department names and these are my commands non worked properly:
```
select emp_name
from employees
select dep_name
from Department
select emp_name
from employees
union
select dep_name
from Department
select emp_name, dep_name
from Department
cross join employees
SELECT employees.emp_name, Department.dep_name
FROM employees, Department
where employees.emp_name = Department.dep_name
select emp_name, Department.dep_name
from employees
inner JOIN Department on employees.emp_name = Department.dep_name
select
count(distinct employees.emp_name)
from
employees
where
employees.emp_name not in (select distinct Department.dep_name
from Department)
select (employees.emp_name)
from employees
where employees.emp_name not in (select Department.dep_name
from Department)
```
Also I want to select employee name and sum of their salary who are working hour is greater than or equal 20 and my command didn't work:
```
select
emp_name, sum(salary)
from
employees
union
select
hurs
from
works
where
hurs >= 20
```
Where did I go wrong here? | First, to get the workers' name and their department, you should be linking table `employees` and `department` using `department_id`, not name..
```
select emp_name,Department.dep_name
from employees inner JOIN Department
on employees.department_id = Department.Department_id
```
and for the employees whose working hours are >=20:
```
select employees.emp_name
from employees join works
on employees.emp_no=works.emp_no AND works.hurs>=20
```
and their total salary:
```
select sum(employees.salary)
from employees join works
on employees.emp_no=works.emp_no AND works.hurs>=20
```
note: `inner join` and `join` are the same thing..
In short, you should realize that linking the tables using `join` is relatively intuitive..
you are linking them based on the "same" column that the both tables own..
[one of them is a foreign key of the other (primary) key]
# UPDATE:
you can display the employees' names and their total salary together as the following, but it would seem redundant..
```
select employees.emp_name, sum(employees.salary)
from employees join works
on employees.emp_no=works.emp_no AND works.hurs>=20
group by employees.emp_name
``` | To union two `SELECT` results they have to have
* same selected column count
* same type of
What you actually want to use is `INNER JOIN` :
```
SELECT emp_name,sum(salary) FROM employees
INNER JOIN works ON employees.emp_no = works.emp_no
WHERE works.hurs >= 20
``` | How can I select two columns from two tables? | [
"",
"sql",
""
] |
I am learning SQL currently and I have a question. I have two tables called "vehicul" and proprietate.
The first table (vehicul) looks like this:
```
id nr_vehicul marca id_marca tip culoare capacitate_cilindrica
1 DJ-01-AAA Mercedes 1 CLK 350 negru 3500
2 DJ-01-BBB Mercedes 1 S 500 silver 5000
3 DJ-01-CCC Mercedes 1 ML 550 alb 5500
4 DJ-01-DDD BMW 2 325 galben 2500
5 DJ-01-EEE BMW 2 X5 negru 350
```
And the second table (proprietate) looks like this:
```
id serie_buletin cnp nr_vehicul data_cumpararii pret
1 AK162332 2006036035087 DJ03AAA 2014-05-01 35000
2 AK162332 2006036035087 DJ03BBB 2014-05-02 90000
3 AK176233 6548751520125 DJ03CCC 2014-05-03 55000
4 BZ257743 6548751520125 DJ03DDD 2014-05-04 25000
5 BZ257743 2006036035087 DJ03EEE 2014-05-05 63000
```
I want to display the column "marca" from the first table and the column "price" from the second, but like this.
```
marca | pret
Mercedes | 180000
BMW | 88000
```
Basically I have three Mercedes cars and two BMW cars, how can I display Mercedes one time and the prices of those three summed up? | You need to join two tables and GROUP them based on `marca` field and sum `pret`
```
select marca, sum(pret)
from table1 as t1, table2 as t2
where t1.id=t2.id
group by marca
```
Here I'm assuming that `id` field is joining two tables, (but as I can see from your sampel data it isn't relating to each-other actually)
**EDIT**
I think you are missing `id_marca` field in `table2`. If its there then it would join to that column as below example:
```
select marca, sum(pret)
from table1 as t1, table2 as t2
where t1.id_marca=t2.id_marca
group by id_marca;
``` | use this requeste
```
select marca, sum(pret)
from vehicul as Ve, proprietate as Pr
where Ve.nr_vehicul=PR.nr_vehicul
group by marca
```
or
```
select marca, sum(pret)
from vehicul as Ve
where Ve.id in(select nr_vehicul from proprietate)
group by marca
``` | MySQL, two tables displaying information from both tables | [
"",
"mysql",
"sql",
""
] |
My mind has gone blank...I am missing something obvious trying to write a small script:
I have one table with various ID's:
```
TBL_USETHISID
nextid int
```
I have another table with references:
```
TBL_REFS
ref varchar(6)
thisdate datetime
nextid int
```
I want to take the ID from TBL\_USETHISID and then update TBL\_REFS so each row's ID is one more than the previous. I will then select the max(nextid) from TBL\_REFS and update TBL\_USETHISID with the highest.
I am struggling a bit with this, we have to use this instead of auto-incrememnt fields as these ID's are used across multiple tables.
Obviously I have tried:
```
UPDATE TBL_REFS FROM TBL_USETHISID
SET nextid = TBL_USETHISID.nextid + 1
```
Thanks for all your help in advance.
EDIT - Sample data:
TBLUSETHISID:
```
nextid
7001
```
TBL\_REFS
```
ref thisdate nextid
0000123 2012-10-02 00:00:00
0000124 2012-10-02 00:00:00
0000125 2012-10-02 00:00:00
```
After update:
TBL\_REFS
```
ref thisdate nextid
0000123 2012-10-02 00:00:00 7001
0000124 2012-10-02 00:00:00 7002
0000125 2012-10-02 00:00:00 7003
```
Then I would UPDATE TBL\_USETHISID FROM TBL\_REFS a set nextid = max(a.nextid)+1 to update the original table. I hope my formatting is correct, i idented like code for readability. | I would strongly advise you to use SEQUENCEs. That is idiomatic Ingres approach (actually, sequences are SQL:2003 standard, if I remember well, so every good RDBMS which supports SQL should support them).
Unfortunately Actian moved the documentation to a new system which makes it very difficult to create a direct link to a page describing something, so I can't really give you a link here. Please go to <http://docs.actian.com> , pick Ingres 10 docs (in Options), and open the SQL reference.
In short, make a sequence called, say `TBL_REFS_SEQ`:
```
CREATE SEQUENCE TBL_REFS_SEQ; -- Also grant it
```
Then you can do something like:
```
UPDATE TBL_REFS
FROM TBL_USETHISID
SET nextid = TBL_REFS_SEQ.NEXTVAL;
```
Sequence also has the `CURVAL` property.
NOTE: Keep in mind that you need to grant privileges to this newly created sequence if you want it to be accessable by certain users/roles.
From the *Ingres 10.0 SQL Reference Guide*:
> A NEXT VALUE or CURRENT VALUE expression on a particular sequence is evaluated once per row inserted by an INSERT statement, updated by an UPDATE statement, or added to the result set of a SELECT statement. If several occurrences of a NEXT VALUE or CURRENT VALUE expression on the same sequence are coded in a single statement, only one value is computed for each row touched by the statement. If a NEXT VALUE expression and a CURRENT VALUE expression are coded on the same sequence in the same statement, the NEXT VALUE expression is evaluated first, then the CURRENT VALUE expression (assuring they return the same value), regardless of their order in the statement syntax. | The most simplest way is through `LOOPS` although not the most efficient way. Also not sure about the syntax in `ingres` as I have never worked on it.
It is also possible through a CTE (again not sure if CTEs work in ingres). Will try and give a solution for that as well.
Till then Check the below code
```
--simulated table structure
DECLARE @TBLUSETHISID TABLE
(
nextid INT
)
DECLARE @TBL_REFS TABLE
(
ref varchar(6),
thisdate datetime,
nextid int
)
-- values for testing
INSERT INTO @TBLUSETHISID VALUES(7001);
INSERT INTO @TBL_REFS VALUES('000123', '2012-10-02 00:00:00', null);
INSERT INTO @TBL_REFS VALUES('000124', '2012-10-02 00:00:00', null);
INSERT INTO @TBL_REFS VALUES('000125', '2012-10-02 00:00:00', null);
--solution starts from here
DECLARE @StartCount INT, @TotalCount INT, @REF VARCHAR(6)
SELECT @TotalCount = COUNT(*) - 1 FROM @TBL_REFS;
SET @StartCount = 0;
WHILE(@StartCount <= @TotalCount)
BEGIN
SELECT @REF = ref FROM (SELECT ROW_NUMBER() over(ORDER BY ref) AS ROWNUM, * FROM @TBL_REFS) as tbl WHERE ROWNUM = @StartCount + 1
UPDATE @TBL_REFS
SET nextid = (SELECT nextid + @StartCount FROM @TBLUSETHISID)
WHERE ref = @REF
SET @StartCount = @StartCount + 1
END
UPDATE @TBLUSETHISID
SET nextid = (SELECT MAX(nextid) + 1 FROM @TBL_REFS)
SELECT * FROM @TBLUSETHISID
SELECT * FROM @TBL_REFS
```
**EDIT:**
A better solution than `LOOP`. The table simulation and test value insertion remains as per the above solution. Of course the problem of `Ingres doesn't support scalar queries` remains so you have to find a work around for this.
```
UPDATE tbl2
SET nextid = (tbl.nextid + ROWNUM - 1)
FROM
(SELECT ROW_NUMBER() over(ORDER BY ref) AS ROWNUM,
ref,
thisdate,
(SELECT nextid FROM @TBLUSETHISID) AS nextid FROM @TBL_REFS) tbl
INNER JOIN @TBL_REFS tbl2
ON tbl.ref = tbl2.ref
```
Hope this helps | SQL Update, incrementing value by 1 | [
"",
"sql",
"ingres",
""
] |
I have a table in database and it has a column named 'Modified date'. Whenever i edit some data from the form in asp.net web form i should be able to fill the database table column 'Modified date' with the current date automatically.
Is there any way out for it.I am stuck with it. | set
> getdate()
something like this:
```
ALTER TABLE [TableName] ADD DEFAULT (getdate()) FOR [ColumnName]
Go
```
as default in your table will give you current insert date and time for Sql server
There are two possible ways :
> 1. From your code behind
> 2. From Select Query from Database
example to select only date from date time :
```
//from code behind
Variable_Name = DateTime.Now.ToString("dd/MM/yyyy");
```
or
```
-- from Database query
SELECT CONVERT (DATE, GETDATE())
``` | You can do it either as Krunal says or hardcode in your insert query in `C#` (or `VB)`:
```
Insert into..... values ( ...., SELECT convert(varchar, getdate(), 106),...,)
```
this inserts into format: `dd/mmm/yy` | How to get current date in sql | [
"",
"asp.net",
"sql",
""
] |
I used to know how to do this, but I can’t seem to remember or find the answer.
I want to return data from a table and then just add an extra column with a set value (which does not need to be saved). So, it is not an `UPDATE` issue. Just a `SELECT` with that extra column.
Original table:
```
| id | col1 | col2 |
| 1 | value1 | value2 |
```
Return something like this:
```
| id | col1 | col2 || tmpCol |
| 1 | value1 | value2 || 12:48 |
``` | It's as simple as:
```
SELECT id, col1, col2, '12:48' AS tempCol
``` | use this
```
select id,col1,col2, '12.48' as tempcol
``` | MySQL SELECT with an extra column containing a string | [
"",
"mysql",
"sql",
"string",
"select",
""
] |
I have a column of USD and EUR currencies and would like to multiply the values to the corresponding exchange in chilean pesos. So far I know how to extract the contracts that are in USDand the ones that are in EUR but I don't kow how to multiply each value by its own exchange rate. I think it could be something like:
```
SELECT contracts.value, contracts.currency
FROM contracts
WHERE contracts.currency='USD' then contracts.value=contracts.value*500
OR contracts.currency='EUR' then contracts.value=contracts.value*750
```
Thank you agian for the help! | You can filter your `contracts.value` by `contracts.currency` using `CASE` statement :
```
SELECT contracts.currency
, CASE WHEN contracts.currency = 'USD' THEN contracts.value*500
WHEN contracts.currency = 'EUR' THEN contracts.value*750
ELSE contracts.value
END
FROM contracts
``` | You can do that in the select clause:
```
SELECT IF(contracts.currency='USD', contracts.value*500, contracts.value*750) as amount
FROM contracts
```
Documentation: <http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html> | Multiplying column if statement is true | [
"",
"mysql",
"sql",
"if-statement",
""
] |
When I do a SELECT statement with an AS definement and i want to filter on that it give the folowing error: #1054 - Unknown column 'TimeInSeconds' in 'where clause'
Code:
```
Select Id, time/10000000 as TimeInSeconds FROM Results WHERE
TimeInSeconds > 5 AND
TimeInSeconds < 36000
```
I understand the error that TimeInSeconds is not part of the original table, but are there ways to work with these defined collumns? | You can also use `HAVING` clause to filter out the results of custom aliases
```
Select Id, `time`/10000000 as TimeInSeconds
FROM Results
HAVING TimeInSeconds > 5 AND TimeInSeconds < 36000
```
Or repeat the expression using `WHERE` clause
```
Select Id, `time`/10000000 as TimeInSeconds
FROM Results
WHERE (`time`/10000000) > 5 AND (`time`/10000000) < 36000
``` | One option is to put the results in a `subquery`:
```
Select Id, timeinseconds
From (Select Id, time/10000000 as TimeInSeconds FROM Results) t
Where TimeInSeconds > 5 AND TimeInSeconds < 36000
``` | MYSQL: Doing a where on a own defined parameter in SELECT | [
"",
"mysql",
"sql",
"select",
"parameter-passing",
"where-clause",
""
] |
I have a large (3 million rows) table of transactional data, which can be simplified thus:
```
ID File DOB
--------------------------
1 File1 01/01/1900
2 File1 03/10/1978
3 File1 03/10/1978
4 File2 15/07/1997
5 File2 01/01/1900
6 File2 15/07/1997
```
In some cases there is no date. I would like to update the date field so it is the same as the other records for a file which has a date. So record 1's DOB would become 03/10/1978, because records 2 and 3 for that file have that date. Likewise record 5 would become 15/07/1997.
What is the most efficient way to achieve this?
Thanks. | Supposing your table is called "Files", then this will work:
```
UPDATE f1 SET f1.DOB=f2.MaxDOB
FROM files f1
JOIN (SELECT File, MAX(DOB) AS MaxDOB FROM files GROUP BY File) f2 ON
f2.File=f1.File;
```
As far as performance is concerned, it probably won't get much more efficient than this, but you do need to insure there is an index on the (File, DOB) column set. 3 million records is a lot and this query will also update records that do not need it, but filtering those out would require a much more complex join. Anyway... you better check the query plan. | I dont know about most efficient way, but i can think of one solution...create a temp table with following query. Though i am not sure about exact keywords of sqlserver 2008, but this might work or you may need to change key word like to\_date and its format.
create table new\_table as (
select file,min(DOB) as default\_date, max(DOB) as fixed\_date from three\_million\_table group by file having min(dob)= to\_Date('01/01/1900','dd/mm/yyyy') )
so your new table will have
column headers: file, default\_date,fixed\_date
values: File1, 01/01/1900, 03/10/1978
Now it may not be wise to run update on three\_million\_table, but if you think it is ok then:
update T1
SET T1.DOB = T2.fixed\_date
FROM three\_million\_table T1
INNER JOIN new\_table T2
ON T1.file = T2.file | Updating one column with the value from another, based on another common column | [
"",
"sql",
"sql-server-2008",
""
] |
I have record of students, every day they undertakes a driving test =, I would like to calculate total number of students who have passed and failed their driving test for today's date e.g
```
StudentName Status date pass fail
test1 something 2014-05-14 1 0
test2 something 2014-05-14 0 1
test1 something 2014-04-14 0 1
test1 something 2014-03-14 0 1
```
At the moment I have this query - `select count(case pass where 1 then 1 else null end) As TotalPassed, count(case pass where 1 then 1 else null end) as Totalfailed from DatabaseName where date>='2014-05-14'` The problem is this query only search for total record from 2014-05-14, but what I want is total number of record for a specific student. For this query I get result as;
```
StudentName Status date pass fail
test1 Something 2014-05-14 1 0
test2 something 2014-05-14 0 1
```
But what I need is the query to calculate the total number of time that each person have passed or failed his/her exams, so the expected result should be:
```
StudentName Status date pass fail
test1 something 2014-05-14 1 2
test2 something 2014-05-14 0 1
``` | You should use `SUM` instead of `COUNT`, and add a `GROUP BY` in the end.
```
SELECT StudentName,
MAX(date) as date,
SUM(pass) As TotalPassed,
SUM(fail) As Totalfailed,
SUM(pass) + SUM(fail) as TotalTriesVersion1,
COUNT(*) as TotalTriesVersion2
FROM Table1
GROUP BY StudentName
```
And [here](http://sqlfiddle.com/#!2/a34327/8) is the sqlfiddle (next time, please provide it yourself :) )
Bonus : I gave you two ways of computing the total number of time each student has **taken** the exam, as I understood from the comments that you wanted to have this too. | You need to use the GROUP BY Clause like this:
```
SELECT COUNT(CASE pass WHERE 1 THEN 1 ELSE NULL END) AS TotalPassed,
COUNT(CASE pass WHERE 1 THEN 1 ELSE NULL END) AS Totalfailed FROM DatabaseName
WHERE date>='2014-05-14' GROUP BY StudentName
``` | Count total number of records | [
"",
"sql",
""
] |
I am executing the below query in sql-server-2008-R2 which gives me output as I wanted(i.e, number of rows) but, I want to store the result in form of a multi-columned row(s) in a variable.
```
declare @rCount int
declare @kuri nvarchar(max)
declare @IDs nvarchar(max)
select @rCount=10
set @kuri='select top '+cast(@rCount as varchar)+' FLD295,FLD9 from tableName (nolock) ORDER BY NEWID()'
execute(@kuri)
```
I had done this earlier but it was different query where I need to concatenate the result of both the queries in to one column (assigning and display)
```
select @IDs=CAST(isnull(@IDs ,'')as varchar)+CAST(COALESCE(fld9,',')as varchar) from table1307 (nolock) ORDER BY NEWID()
``` | ```
DECLARE @T1 TABLE (
FLD9 bigint
, FLD295 nVARCHAR(max)
)
insert into @T1(,FLD295,FLD9)
select top(@rCount) FLD295,FLD9 from tableName (nolock)
ORDER BY NEWID()
select * from @T1
select @IDs=CAST(isnull(@IDs ,'')as varchar)+CAST(COALESCE(fld9,',')as varchar) from @T1
``` | I think you're missing the face that you can do
```
declare @i int=3
select top(@i) .... –
```
2008 does support dynamic top
I hope you know that result should be single. , otherwise , it can't be possible (unless you're doing `insert into...`
if you're asking about how to concatenate ( cte is jsut table , ignore it)
 | need to assign values from sql query in single instance | [
"",
"sql",
"sql-server",
""
] |
Hello so I have two tables and I want to copy one column from table1 to table2.
```
SET @m=0;
SELECT column INTO @m FROM table1;
UPDATE table2 SET column = @m;
```
Basically I tried to insert into the column in table2 the values from column in table1. What am I doing wrong?
LE: I tried the INSERT INTO and it worked in the end but it inserted the values after my desired rows. Basically all my rows had the values 0 and it created another set of rows with the correct values. | Syntax is Correct but when you are copying you should take care about types ...
**types** should be compatible to each other
```
INSERT INTO table (column)
SELECT a_column
FROM a_table
--- optional (multiple) JOINs
--- and WHERE
--- and GROUP BY
--- any complex SELECT query
``` | Try this syntax: `INSERT INTO table2 (column) SELECT column FROM table1`
Don't need VALUES and parenthesis. | MySQL copying a column from another table | [
"",
"mysql",
"sql",
""
] |
I want to create a group of users only if the same group does not exist already in the database.
I have a GroupUser table with three columns: a primary key, a GroupId, and a UserId. A group of users is described as several lines in this table sharing a same GroupId.
Given a list of UserId, I would like to find a matching GroupId, if it exists.
What is the most efficient way to do that in SQL? | Let say your UserId list is stored in a table called 'MyUserIDList', the following query will efficiently return the list of GroupId containing exactly your user list. (SQL Server Syntax)
```
Select GroupId
From (
Select GroupId
, count(*) as GroupMemberCount
, Sum(case when MyUserIDList.UserID is null then 0 else 1 End) as GroupMemberCountInMyList
from GroupUser
left outer join MyUserIDList on GroupUser.UserID=MyUserIDList.UserID
group by GroupId
) As MySubQuery
Where GroupMemberCount=GroupMemberCountInMyList
``` | There are couple of ways of doing this. This answer is for sql server only (as you have not mentioned it in your tags)
1. Pass the list of userids in comma seperated to a stored procedure and in the SP create a dynamic query with this and use the `EXEC` command to execute the query. [This](http://www.mssqltips.com/sqlservertip/1160/execute-dynamic-sql-commands-in-sql-server/) link will guide you in this regard
2. Use a table-valued parameter in a SP. This is applicable to sql server 2008 and higher only.
The following link will help you get started.
<http://www.codeproject.com/Articles/113458/TSQL-Passing-array-list-set-to-stored-procedure-MS>
Hope this helps. | Check if a list of items already exists in a SQL database | [
"",
"sql",
"many-to-many",
""
] |
So i'm just wondering how I would go about getting the a merged list of two tables,
one with all the required rows, and the second with extra data to be associated with the first. 
So with table 1 and 2 I want to get 3, would this be able to be done as a query? | So if the "empty" value in column coming from table2 can just be NULL, you can do a LEFT JOIN
```
select
t1.col1, --this is A, B, C
t1.col2,
t1.col3,
t2.col4 -- this is the fourth column
from Table1 t1
left join Table2 t2 on t1.Col1 = t2.Col1
```
see [SqlFiddle](http://sqlfiddle.com/#!6/98ebf/1)
If you wanna be sure to join only if the 3 columns are the same, just add conditions to the left join
```
on t1.Col1 = t2.Col1 and t1.Col2 = t2.Col2 and t1.Col3 = t2.Col3
``` | Use Exists
```
SELECT T1.Column1, T1.Column2, T2.Column3
FROM T1, T2
WHERE T1.Column1 IN
(SELECT Column1 FROM T1);
``` | Query to merge results with same values + extra column | [
"",
"sql",
"sql-server",
""
] |
I am trying to add two columns to the query below:
* 1st column would be the % of free space = `freespace/capacity`
* 2nd column would be the amount of used space = `capacity-freespace`
This is my query
```
SELECT SystemName, Caption, Label, Capacity, FreeSpace
FROM CCS_Win32_Volume
ORDER BY SystemName, Caption
USE [CentralConfigurationStore]
GO
```
Would adding it to the query or doing it after and joining the two tables be the better approach?
If anyone could help me out with this it would be appreciated! | Calculated fields will not add much overhead when you add them right into the query, since the data you're calculating on has already been read from disk.
```
SELECT SystemName, Caption, Label, Capacity, FreeSpace,
100*freespace/capacity [% of free space],
capacity-freespace [used space]
FROM CCS_Win32_Volume
ORDER BY SystemName, Caption
```
[An SQLfiddle to test with](http://sqlfiddle.com/#!3/8cdfb/4). | I think the question was the approach, not the actual T-SQL...
Unless your query is used elsewhere and changing it might break something, then I would update your existing query.
If it is used elsewhere and it's going to be a lot of work to update all the related processes/queries then I would create a separate query with the complete results. There seems little point in creating a query with just the calculated values in because, as you stated, you'll then have to join it back to your original query, which just seems like more work for nothing.
Anyway, that's just my personal opinion.
Regards,
Al. | When to add calculated custom columns to a query - right away or by using a join | [
"",
"sql",
"sql-server",
""
] |
I have a database table that stores data to show on a report. Each time records are inserted into the database, another row is added except the ReportNumber row is incremented. I've been searching and can't seem to find anyone else who may have asked this. I need the stored procedure to get the latest report info (highest number in the ReportNumber row). How can I do this? Here's an example.
```
Year Data ReportNumber
2014 135 1
2014 135 2
2014 136 1
2014 136 2
```
When I run the report I only want to show the latest data based on the ReportNumber (2 in this case) | Does this do it:
```
select *
from Table
where ReportNumber in (select max(ReportNumber)
from Table)
``` | Why not use `order by` like
```
select * from
report_table
order by
ReportNumber desc
```
(OR)
```
select * from
report_table
where ReportNumber = (select max(ReportNumber) from report_table)
``` | Filter SQL results by highest number in column | [
"",
"sql",
"sql-server",
""
] |
```
DECLARE @DATA TABLE
(
Id int,
Value int
)
INSERT INTO @DATA VALUES (1, 10)
INSERT INTO @DATA VALUES (2, 20)
INSERT INTO @DATA VALUES (3, 30)
INSERT INTO @DATA VALUES (4, 40)
DECLARE @TO_FILL TABLE
(
Id int,
Value int
)
INSERT INTO @TO_FILL VALUES (1, 100)
INSERT INTO @TO_FILL VALUES (3, 300)
DECLARE @METHOD int = 0
IF @METHOD = 0
BEGIN
UPDATE @DATA
SET Value = source.Value
FROM @TO_FILL source
WHERE [@DATA].Id = source.Id
END
ELSE
BEGIN
UPDATE @DATA
SET Value = source.Value
FROM @DATA destination
INNER JOIN @TO_FILL source ON destination.Id = source.Id
END
SELECT *
FROM @DATA
```
The idea is to update the table @DATA with the values from @TO\_FILL, whenever the id matches. Whether @METHOD is set to 0 or not, this query will provide the same result.
I could understand the logic behind the block that uses the WHERE clause, which would be :
* Update table @DATA
* For each row, modify column Value
* Use the column Value from table @TO\_FILL, alias source
* Do the modification whenever both columns Id match
But I have a hard time figuring the reasoning behind the second block, that uses the INNER JOIN clause. In my eyes, there are three 'temporary instances' of table : @DATA, @DATA alias destination, @TO\_FILL alias source. destination and source are being joined to determine the set of rows that have to be modified (let's call it @DATA\_TO\_FILL), but I can't see how it is linked to the first table (@DATA). Since there are no WHERE or INNER JOIN clause between @DATA and @DATA\_TO\_FILL, how come it works ? | From the relevant [TechNet page](http://technet.microsoft.com/en-us/library/ms177523.aspx):
> If the object being updated is the same as the object in the FROM clause and there is only one reference to the object in the FROM clause, an object alias may or may not be specified. If the object being updated appears more than one time in the FROM clause, one, and only one, reference to the object must not specify a table alias. All other references to the object in the FROM clause must include an object alias.
In other words, in your example, the fact that you assign an alias to @DATA in the FROM clause doesn't prevent SQL Server from recognizing that it's the same table you're updating, since there's no ambiguity. However, if your FROM clause involved joining @DATA to itself, then you would have to specify which is the table to be updated by omitting an alias from one instance. | Both queries are essentially doing the same thing, difference is in the syntax.
*1st Query*
Its is using old join syntax where join condition is mentioned in where clause something like this...
```
SELECT *
FROM table1 , Table2
WHERE Table1.ID = Table2.ID
```
*2nd Query*
your second block uses newer ansi join syntax, key word `JOIN` is used and join condition is mentioned in `ON` clause, which is something like this.....
```
SELECT *
FROM table1 INNER JOIN Table2
ON Table1.ID = Table2.ID
```
The result set will be the same from both queries but its only the syntax difference, 2nd method is preferred syntax. stick to it. | What is the difference between UPDATE FROM WHERE and UPDATE FROM INNER JOIN? | [
"",
"sql",
"sql-server",
""
] |
I need to insert into a mysql table. However, It should insert only if a conditions is satisfied. So I want something like this to happen
```
INSERT INTO table_name(name,qty,code) VALUES(SELECT i.name,i.qty,i.code FROM table2 i);
```
For a condition like this
```
IF i.code == 'abcd' && i.name == 'def' THEN perform insert ELSE don't insert
```
I can't use a WHERE clause because I want to select and insert all codes except the case when it equals 'abcd', in which case I want to insert based on the condition. | @strawberry answered this question in the comments. It's a simple answer but somehow really nice. Here is the answer
```
INSERT INTO table_name(name,qty,code) VALUES
(
SELECT i.name,i.qty,i.code FROM table2 i
WHERE (i.code = 'abcd' AND i.name = 'def') OR i.code != 'abcd'
)
``` | first insert all the rows from table2 for code = 'abcd' and name = 'def'
```
INSERT INTO table_name SELECT i.name,i.qty,i.code FROM table2 i where i.code = 'abcd' and i.name = 'def'
```
Now insert conditionally other rows | Selectively inserting into a mysql table | [
"",
"mysql",
"sql",
""
] |
I want to limit the count to 5 using `COUNT(*)` and `group by` but it returns all the rows.Consider I have a table names tbhits
```
tbhits
id | uname
------------------------
101 | john
101 | james
101 | henry
101 | paul
101 | jacob
101 | jaden
101 | steve
101 | lucas
102 | marie
```
SELECT id,COUNT(\*) as 'hits' FROM tbhits GROUP BY id
returns
```
id | hits
--------------------
101 | 8
102 | 1
```
But I want the group by to limit maximum count to 5.
Say I have got 1000 rows I dont want to count them all, if rows are just greater than 5 then just display `5+`
I tried using LIMIT 5 but it does not seem to work
`SELECT id,COUNT(*) as 'hits' FROM tbhits GROUP BY id LIMIT 5` does not work.
I also used `WHERE Clause`
SELECT id,COUNT(\*) as 'hits' FROM tbhits WHERE id = 101 GROUP BY id LIMIT 5
but it stil returns hits as 8.
```
id | hits
--------------------
101 | 8
```
Any help is greatly appreciated. | `LIMIT` is intended to limit the number of rows you'll get from your query. I suggest you use the `COUNT` function as follows :
```
SELECT id, CASE WHEN COUNT(*) < 6 then COUNT(*) ELSE '5+' END as 'hits'
FROM tbhits
GROUP BY id
```
More details about selecting the minimum of two numbers [here](https://stackoverflow.com/questions/1947753/getting-the-minimum-of-two-values-in-sql), and [here goes the sqlfiddle](http://sqlfiddle.com/#!2/2c467/5) (consider providing it yourself next time).
Note that I went for 6 instead of '5+' on my first suggestion, because you should not, in my opinion, mix data types. But putting 6 is not a good solution either, because someone not aware of the trick will not notice it ('5+', at least, is explicit)
As far as performance is concerned, AFAIK you should not expect MySQL to do the optimization itself. | LIMIT on GROUP BY clause won't actually limit the counts, it will limit the rows being outputed.
Try using `if` statement to compare count result,
```
SELECT id,if(COUNT(*)>5,'5+',COUNT(*)) as 'hits'
FROM tbhits
GROUP BY id
```
O/p:
```
id | hits
--------------------
101 | 5+
102 | 1
```
Regarding performance issue, AFAIK `GROUP BY` will always lead to lead down performance and there is no **direct way** to limit counts in `GROUP BY` clause. You will have to go with either `IF` or `CASE` statement if you want solution from MySQL. Otherwise go with `PHP` itself.
Moreover you should have a look at [`GROUP BY optimization`](http://dev.mysql.com/doc/refman/5.0/en/group-by-optimization.html) | Limit the count using GROUP BY | [
"",
"mysql",
"sql",
""
] |
I am tryng to compare race codes in two different tables joining on a number id in each table, one table is in fixed positional format. I am getting an error on the '.' between T2.DSNumber on line 5
```
select
T1.SNumber,
T1.Racecode1,
T1.Race1 ,
SUBSTRING(rec,1,6) as T2.DSNumber,
SUBSTRING(rec,175,2) as T2.DSRaceCode1,
SUBSTRING(rec,251,12) as T2.DSRaceText1
from scerts T1
INNER JOIN DS2012 T2
on T1.SNumber = T2.DSNumber
where right(T1.SNumber,6) = T2.DSNumber and T1.Racecode1 <>T2.DSRaceCode1
and T1.FLAG = 'o'
and year(cast(T1.DDate as date)) ='2012'
order by T1.SNumber
``` | If i am not wrong, you are using SQL Server. In your query the below part is wrong
```
SUBSTRING(rec,1,6) as T2.DSNumber,
```
should be
```
SUBSTRING(rec,1,6) as DSNumber,
SUBSTRING(rec,175,2) as DSRaceCode1,
SUBSTRING(rec,251,12) as DSRaceText1
``` | Others apparently are close with different answers, but your issue is that your second table (T2) does not actually have columns for "DSNumber" and "DSRaceCode1" as you are pulling those from the substring components. Therefore, those substring references need to be applied to your join (or WHERE). I have formatted to JOIN condition SQL format. You can't give an alias.column as a column name as you attempted to do, but enough info to provide what SHOULD be proper syntax for you to move forward.
Also, for future, and hopefully can apply to what you have via table structure changes, use id-based columns for joins and not getting into "merged" fields into a single will kill your performance, querying and support down-stream.
```
select
T1.SNumber,
T1.Racecode1,
T1.Race1,
SUBSTRING(T2.rec,1,6) as DSNumber,
SUBSTRING(T2.rec,175,2) as DSRaceCode1,
SUBSTRING(T2.rec,251,12) as DSRaceText1
from
scerts T1
INNER JOIN DS2012 T2
on right(T1.SNumber,6) = SUBSTRING(T2.rec,1,6)
AND T1.Racecode1 <> SUBSTRING(T2.rec,175,2)
where
T1.FLAG = 'o'
and year(cast(T1.DDate as date))
```
Also.. seeing sample data from each respective table would definitely have helped the many others that tried to answer your question :) | inner join aliases not working | [
"",
"sql",
"t-sql",
""
] |
I have written a procedure which takes several input parameters.
I need to validate the input.
If they are valid values they have to be present in the database table - attribute\_values.
The problem is attribute\_values table contains million records.
I am now supposed to improve the performance of select query.
For validating 1 input parameter I am doing something like this.
```
SELECT COUNT(1) INTO COUNT_VAR
FROM ATTRIBUTE_VALUES A
WHERE A.ATTRIBUTE_VALUE = input_paramater1;
IF COUNT_VAR = 1 THEN
SELECT ATTRIBUTE_VALUE_ID INTO MYVAR1
FROM ATTRIBUTE_VALUES A
WHERE A.ATTRIBUTE_VALUE = input_paramater1;
END IF;
other_procedure(MYVAR1);
```
Any suggestions for improving performance of selecting from a table which contains a million records.
Also out of count(\*) and count(1) which is better. | Rather than doing a `SELECT COUNT(*)...` followed by a `SELECT ID...`, both against the same table, I suggest you rework this logic as follows:
```
BEGIN
SELECT ATTRIBUTE_VALUE_ID
INTO MYVAR1
FROM ATTRIBUTE_VALUES A
WHERE A.ATTRIBUTE_VALUE = INPUT_PARAMETER1 AND
ROWNUM = 1;
COUNT_VAR := 1;
EXCEPTION
WHEN NO_DATA_FOUND THEN
COUNT_VAR := 0;
MYVAR1 := NULL;
END;
OTHER_PROCEDURE(MYVAR1);
```
This helps two ways. First, in my experience `SELECT COUNT...` is *slow*, so I try to avoid it whenever possible. Second, this not only saves a second query but lets you take advantage of the standard exception handling built in to PL/SQL.
Share and enjoy.
**EDIT:** given OP's revelation (in comments to the question, above) that ATTRIBUTE\_VALUES.ATTRIBUTE\_VALUE is not unique I've updated the code above so that it will not fail if more than one row would be returned. | For these queries, I would suggest an index:
```
create index attribute_values_attribute_value on attribute_values(attribute_value);
```
This should suffice for your purposes. | how to improve performance of select | [
"",
"sql",
"oracle",
"stored-procedures",
"plsql",
""
] |
I found this character while reading some blog of pl sql `<< some text >>` .
I found this character from following blog <http://www.oracle-base.com/articles/8i/collections-8i.php> | It's often used to label loops, cursors, etc.
You can use that label in [`goto`](http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/goto_statement.htm) statements. Else, it is just 'comment'.
Sample from Oracle:
```
DECLARE
p VARCHAR2(30);
n PLS_INTEGER := 37; -- test any integer > 2 for prime
BEGIN
FOR j in 2..ROUND(SQRT(n)) LOOP
IF n MOD j = 0 THEN -- test for prime
p := ' is not a prime number'; -- not a prime number
GOTO print_now; -- << here is the GOTO
END IF;
END LOOP;
p := ' is a prime number';
<<print_now>> -- << and it executes this
DBMS_OUTPUT.PUT_LINE(TO_CHAR(n) || p);
END;
/
``` | As others have said, `<<some_text>>` is a label named "some\_text". Labels aren't often used in PL/SQL but can be helpful in a variety of contexts.
As an example, let's say you have several nested loops, execution has reached the very inner-most level, and the code needs to exit from all the nested loops and continue after the outer-most one. Here a label can be used in the following fashion:
```
<<outer_most_loop>>
LOOP
...
<<next_inner_loop>>
LOOP
...
<<inner_most_loop>>
LOOP
...
IF something <> something_else THEN
EXIT outer_most_loop;
END IF;
...
END LOOP inner_most_loop;
...
END LOOP next_inner_loop;
...
END LOOP outer_most_loop;
-- Execution continues here after EXIT outer_most_loop;
something := something_else;
...
```
Next, let's say that you've got some code with nested blocks, each of which declares a variable of the same name, so that you need to instruct the compiler about which of the same-named variables you intend to use. In this case you could use a label like this:
```
<<outer>>
DECLARE
nNumber NUMBER := 1;
BEGIN
<<inner>>
DECLARE
nNumber NUMBER := 2;
BEGIN
DBMS_OUTPUT.PUT_LINE('outer.nNumber=' || outer.nNumber);
DBMS_OUTPUT.PUT_LINE('inner.nNumber=' || inner.nNumber);
END inner;
END outer;
```
Labels can also be useful if you insist on giving a variable the same name as a column in a table. As an example, let's say that you have a table named PEOPLE with a non-nullable column named LASTNAME and you want to delete everyone with LASTNAME = 'JARVIS'. The following code:
```
DECLARE
lastname VARCHAR2(100) := 'JARVIS';
BEGIN
DELETE FROM PEOPLE
WHERE LASTNAME = lastname;
END;
```
will not do what you intended - instead, it will delete every row in the PEOPLE table. [This occurs because in the case of potentially ambiguous names, PL/SQL will choose to use the column in the table instead of the local variable or parameter](http://docs.oracle.com/cd/B10501_01/appdev.920/a96624/d_names.htm#3693); thus, the above is interpreted as
```
DECLARE
lastname VARCHAR2(100) := 'JARVIS';
BEGIN
DELETE FROM PEOPLE p
WHERE p.LASTNAME = p.lastname;
END;
```
and boom! Every row in the table goes bye-bye. :-) A label can be used to qualify the variable name as follows:
```
<<outer>>
DECLARE
lastname VARCHAR2(100) := 'JARVIS';
BEGIN
DELETE FROM PEOPLE p
WHERE p.LASTNAME = outer.lastname;
END;
```
Execute this and only those people with LASTNAME = 'JARVIS' will vanish.
And yes - as someone else said, you can `GOTO` a label:
```
FUNCTION SOME_FUNC RETURN NUMBER
IS
SOMETHING NUMBER := 1;
SOMETHING_ELSE NUMBER := 42;
BEGIN
IF SOMETHING <> SOMETHING_ELSE THEN
GOTO HECK;
END IF;
RETURN 0;
<<HECK>>
RETURN -1;
END;
```
(Ewwwww! Code like that just feels so wrong..!)
Share and enjoy. | What is << some text >> in oracle | [
"",
"sql",
"oracle",
"plsql",
""
] |
I'm trying to get the quotient of two columns inside the select statement. Here's what I have tried.
```
Select ( select sum(x.amount) amount
from this_table x
where x.acct_no = '52'
) /
( select sum(x.amount) amount
from this_table x
where x.acct_no = '53'
) as amount
from this_table y
join this_table x on x.acct_no = y.acct_no
where x.acct_no = '52' or x.acct_no = '53'
```
When I do this, my amount column just comes out as 1, and I'm positive that isn't what the result should be. Any advice or help? Solution? | This should do as you want:
```
select sum(case when acct_no = '52' then amount else 0 end)
/ sum(case when acct_no = '53' then amount else 0 end) as amount
from this_table
where acct_no in ('52','53')
```
To make the amount column show zero if the divisor is zero (rather than return an error), you can use:
```
select case when sum(case when acct_no = '53' then amount else 0 end) = 0 then 0
else
sum(case when acct_no = '52' then amount else 0 end)
/ sum(case when acct_no = '53' then amount else 0 end) end as amount
from this_table
where acct_no in ('52','53')
```
May be useful if you plan on doing this often and/or using the results in an application where you don't want an error thrown back at you. | FWIW I just had a play in SQLFiddle <http://sqlfiddle.com/#!1/d41d8/1606> , and if you're only after a single row single column result, PostgreSQL seems to allow :
```
WITH Amounts52 as (select 23 as sum52),
Amounts53 as (select 4356 as sum53)
SELECT Amounts52.sum52::float
/ Amounts53.sum53 AS Result
FROM Amounts52, Amounts53
```
So you can put your `Sum()` queries in the two Common Table Expressions and get a the single result - if this approach appeals to you (it has its uses)
Of course it is a lot simpler to use this ( <http://sqlfiddle.com/#!1/d41d8/1924/0> ) :
```
SELECT (select 23 as sum52)
/(select 4356 as sum53)::float AS Answer
``` | How do you divide in the select statement? | [
"",
"sql",
"postgresql",
""
] |
I have three tables towns , patientsHome,patientsRecords
**towns**
> Id
> 1
> 2
> 3
**patientsHome**
> Id | serial\_number
> 1 | 11
> 2 | 12
> 2 | 13
**patientsRecords**
> status | serial\_number
> stable | 11
> expire | 12
> expire | 13
I want to count stable and expire patients from patients records against each Id from towns.
output should be like
**Result**
> Id| stableRecords |expiredRecords
> 1| 1 | 0
> 2| 0 | 2
> 3| 0 | 0 | Try like this :
```
select t.id,case when tt.StableRecords is null then 0 else tt.StableRecords end
as StableRecords,case when tt.expiredRecords is null then 0 else tt.expiredRecords
end as expiredRecords from towns t left join
(select ph.id, count(case when pr.status='stable' then 1 end) as StableRecords,
count(Case when pr.status='expire' then 1 end) as expiredRecords
from patientsRecords pr inner join
patientsHome ph on ph.serial_number=pr.serial_number
group by ph.id ) as tt
on t.id=tt.id
``` | Assuming `patientsHome.ID` is in fact a foreign key to `towns.ID`, you can join the 3 tables, filter as appropriate, group by Town, and count the rows:
```
SELECT t.Id, COUNT(*) as patientCount
FROM towns t
INNER JOIN patientsHome ph
on t.Id = ph.Id
INNER JOIN patientsRecords pr
on ph.serialNumber = pr.serialNumber
WHERE pr.status in ('stable', 'expire')
GROUP BY t.Id;
```
If you also want to classify the status per town:
```
SELECT t.Id, pr.status, COUNT(*) as patientCount
... FROM, WHERE same as above
GROUP BY t.Id, pr.status;
``` | Linking three tables SQL | [
"",
"sql",
"postgresql",
""
] |
We're accessing our database with our server (another computer). Before, I'm able to connect with it but it suddenly stop and now I cant connect and I encounter this error which is error 26 Locating Server.
Others can connect with our server. I don't know what I've done or what I've change with my machine that causes me to not connect with our server. Can anyone suggest what should I do?
I'm using SQL Server 2008 R2.
By the way, I can access our server using Remote Desktop Connection but when I'm connecting using SQL Server 2008 R2, I really can't connect. I'm using the right server name but it doesn't work.
I've tried connecting to other server and It do work. What should I do? I don't know why it happened.
 | Try **flushing your DNS**.
Open a DOS window to do this.
1. Click Start Button
2. Type CMD and press enter
3. Type this into the black window that appears: **ipconfig /flushdns** and press enter you should see:
Windows IP Configuration
Successfully flushed the DNS Resolver Cache.
See if this does not correct your issue. | I tried using the (IP address of the server)\SQLEXPRESS and it do work. Yet I still dont know why It cant access the instance name of the server. | How to resolve Error 26 in SQL Server? | [
"",
"sql",
"sql-server",
"sql-server-2008-r2",
""
] |
Currently have sql returning a result set as below
```
WORKFLOWID UNMATCHEDVALUE MATCHEDADDRESS EXCEPTIONREASON
1001 UNIQUE ADDRESS1 (null)
1001 UNIQUE ADDRESS2 Some Value
```
What I am looking for is a result like this
```
WORKFLOWID UNMATCHEDVALUE MATCHEDADDRESS EXCEPTIONREASON MATCHEDADDRESS2 EXCEPTIONREASON2
1001 UNIQUE ADDRESS1 (null) ADDRESS2 Some Value
```
So the "variant" columns are MatchedAddress and Exception Reason, the other columns will be the same for each record. Note that for each workflow\_id, will always have 2 rows coming back.
I have also created a fiddle to show the schema.
<http://sqlfiddle.com/#!6/f7cde/3> | Try this:
```
;WITH CTE AS
(
SELECT ws.id as WorkflowStepId,
ws.workflow_id as WorkflowId,
sg.unmatchValue as UnmatchedValue,
geo_address as MatchedAddress,
ws.exception_Value as ExceptionReason,
ROW_NUMBER() OVER(PARTITION BY ws.workflow_id ORDER BY ws.id) as RN
FROM workflow_step as ws
INNER JOIN workflow as gw
ON ws.workflow_id = gw.id
INNER JOIN super_group as sg
ON gw.super_group_id = sg.id
INNER JOIN alias on
ws.id = alias.workflow_step_id
)
SELECT WorkflowId,
UnmatchedValue,
MIN(CASE WHEN RN = 1 THEN MatchedAddress END) MatchedAddress,
MIN(CASE WHEN RN = 1 THEN ExceptionReason END) ExceptionReason,
MIN(CASE WHEN RN = 2 THEN MatchedAddress END) MatchedAddress2,
MIN(CASE WHEN RN = 2 THEN ExceptionReason END) ExceptionReason2
FROM CTE
GROUP BY WorkflowId,
UnmatchedValue
ORDER BY workflowId
```
[**Here is**](http://sqlfiddle.com/#!6/f7cde/6) the modified sqlfiddle.
The results are:
```
╔════════════╦════════════════╦════════════════╦═════════════════╦═════════════════╦══════════════════╗
║ WORKFLOWID ║ UNMATCHEDVALUE ║ MATCHEDADDRESS ║ EXCEPTIONREASON ║ MATCHEDADDRESS2 ║ EXCEPTIONREASON2 ║
╠════════════╬════════════════╬════════════════╬═════════════════╬═════════════════╬══════════════════╣
║ 1001 ║ UNIQUE ║ ADDRESS1 ║ (null) ║ ADDRESS2 ║ Some Value ║
╚════════════╩════════════════╩════════════════╩═════════════════╩═════════════════╩══════════════════╝
``` | Try this:
```
SELECT ws.workflow_id as WorkflowId, sg.unmatchValue as UnmatchedValue,
MAX(CASE WHEN ws.id = 1 THEN geo_address END) as MatchedAddress1,
MAX(CASE WHEN ws.id = 2 THEN geo_address END) as MatchedAddress2,
MAX(CASE WHEN ws.id = 1 THEN ws.exception_Value END) as ExceptionReason1,
MAX(CASE WHEN ws.id = 2 THEN ws.exception_Value END) as ExceptionReason2
FROM workflow_step as ws
INNER JOIN workflow as gw on ws.workflow_id = gw.id
INNER JOIN super_group as sg on gw.super_group_id = sg.id
inner JOIN alias on ws.id = alias.workflow_step_id
GROUP BY ws.workflow_id, sg.unmatchValue
```
[**SQL FIDDLE DEMO**](http://sqlfiddle.com/#!6/f7cde/13) | Getting Results from inner join differences on same row | [
"",
"sql",
"sql-server-2012",
""
] |
It is acceptable in Oracle databases the command
```
"SELECT UNIQUE * FROM table"?
```
Or do I have to select the column name for that command to work? | Yes, this syntax is acceptable.
See this [SQLFiddle example](http://sqlfiddle.com/#!4/ce01b/2). | you can use the following query
```
select distinct * from table
``` | Oracle SELECT UNIQUE * FROM TABLE | [
"",
"sql",
"oracle",
""
] |
I have two tables as below:
logs
```
id | user | log_id
---------------------
1 | user1 | abc
2 | user2 | def
3 | user1 | xyz
...
```
users
```
id | user | code
---------------
1 | user1 | 1234
2 | user2 | 9876
3 | user1 | 5678
...
```
I want to add log\_id to `users` and update it with log\_id's from Table1, to make Table2 as below:
```
id | user | code | log_id
---------------------------
1 | user1 | 1234 | abc
2 | user2 | 9876 | def
3 | user1 | 5678 | xyz
...
```
The only way to match rows in logs and users is using the user field, and the chronological order they appear in the tables. `id`, as you may have guessed, is the primary key in both tables.
Much appreciated if someone could help me with the query for this. Thanks. | I figured out the solution. I added 2 columns `rank` and `prev_user` in both tables, and incremented the value for `rank` from 1 for the first record for user\_x to n for the nth record for user\_x, as below:
```
ALTER TABLE users ADD COLUMN rank tinyInt(1);
ALTER TABLE users ADD COLUMN prevuser varchar(50);
SET @prevuser = '';
SET @rank = 0;
UPDATE users
SET rank = (@rank:=IF(@prevuser != user,1,@rank+1)),
prevuser = (@prevuser := user)
ORDER BY user,id;
ALTER TABLE users DROP COLUMN prevuser;
```
and,
```
ALTER TABLE logs ADD COLUMN rank tinyInt(1);
ALTER TABLE logs ADD COLUMN prevuser varchar(50);
SET @prevuser = '';
SET @rank = 0;
UPDATE logs
SET rank = (@rank:=IF(@prevuser != user,1,@rank+1)),
prevuser = (@prevuser := user)
ORDER BY user,id;
ALTER TABLE logs DROP COLUMN prevuser;
```
Now records can be matched between the tables using `user` & `rank`. I added the field `log_id` to `users` and updated it as below:
```
UPDATE users, logs SET users.log_id=logs.log_id WHERE users.user=logs.user AND users.rank = logs.rank;
```
And voila! | If the id fields are always matched then the reply by Ronak Shah would be my choice.
If the ids do not match then possibly something like this:-
Firstly:-
```
ALTER TABLE table1 ADD COLUMN code VARCHAR(25);
```
Then an update like this:-
```
UPDATE table2
INNER JOIN
(
SELECT id, user, code, @rank2:=IF(@prev_user2 = user, @rank2+1, 1) AS rank, @prev_user2 := user
FROM table2
CROSS JOIN (SELECT @rank2:=0, @prev_user2:='') sub2
ORDER BY user, id
) tab_2
ON table2.id = tab_2.id
INNER JOIN
(
SELECT id, user, log_id, @rank1:=IF(@prev_user1 = user, @rank1+1, 1) AS rank, @prev_user1 = user
FROM table1
CROSS JOIN (SELECT @rank1:=0, @prev_user1:='') sub1
ORDER BY user, id
) tab_1
ON tab_1.user = tab_2.user
AND tab_1.rank = tab_2.rank
SET table2.log_id = tab_1.log_id;
```
What this is doing is a pair of sub queries which adds a rank to each tables records (I have added the rank within the user, which should make it cope a bit better if one user on one table has an extra record). The results of these sub queries are joined together, and then joined to table2 to do the actual update (the sub query for table2 to get the rank can be joined to table2 based on id).
This seems to work when done in SQL fiddle:-
<http://www.sqlfiddle.com/#!2/ad8a6b/1> | MySQL - updating table based on chronological order | [
"",
"mysql",
"sql",
"join",
""
] |
i am trying to create new column from existing column(table) in a new table.
this is my old table
```
projectnum allw budjet
648PE2075 152.00 230.00
648PE2075A 33.33 00.00
333AD0221B 125.11 1256.00
123CF0023 125.22 215.33
```
I need to create a new table that have a new column called Project\_code created from projectnum column and all the old columns.
looks like this
```
projectnum Project_code allw budjet
648PE2075 648-075 152.00 230.00
648PE2075A 648-075-A 33.33 00.00
333AD0221B 333-221-B 125.11 1256.00
123CF0023 123-023 125.22 215.33
```
My challeng is when i try to write t\_sql statement. some records of projectnum are 10 character rest 9 character. Help Please | I suggest using `select ... into ... from ...` to create a new table from existing data in one step. For your string operations `substring()` seems appropriate. Please try the following query:
```
select
projectnum,
allw,
budjet,
substring(projectnum, 1, 3)
+ '-'
+ substring(projectnum, 7, 3)
+ case
when len(projectnum) = 10
then '-' + substring(projectnum, len(projectnum) - 1, 1) end
as project_code
into
new_table
from
old_table
```
Read more on `substring()` at the [Microsoft Docs](http://technet.microsoft.com/de-de/library/ms187748.aspx). | ```
SELECT
projectnum,
CASE LEN(projectnum)
WHEN 9 THEN LEFT(projectnum,3) + '-' + SUBSTRING(projectnum,6,3)
WHEN 10 THEN LEFT(projectnum,3) + '-' + SUBSTRING(projectnum,6,3) + '-' + RIGHT(projectnum,1)
END AS Project_code,
allw,
budjet
INTO MyNewTable
FROM MyOldTable
```
Just obviously swap the table names! This will create the new table too, if you already have the table just change it so it reads
```
INSERT INTO MyNewTable(projectnum,Project_code, allw, budjet)
SELECT
projectnum,
CASE LEN(projectnum)
WHEN 9 THEN LEFT(projectnum,3) + '-' + SUBSTRING(projectnum,6,3)
WHEN 10 THEN LEFT(projectnum,3) + '-' + SUBSTRING(projectnum,6,3) + '-' + RIGHT(projectnum,1)
END AS Project_code,
allw,
budjet
FROM MyOldTable
```
There are much more elegant solutions that would allow for more options but hopefully this will work or give you an idea how to solve any other similar issues.
Al. | creating new column from existing column using t-sql | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I need some help with a SQL view please..
I am creating a view to be used for reporting via Crysyal.. One of the fields that I need is a string field that contains three values separated by a character '~' I basically need this splitting out within my Select query within view to three separate fields..
An example is below.. The field is called 'Problem.Description' and contains the following example data..
'Trading~Concession~Telemetry - OCPD / Low Sales'
So, in my sql view I get a single column.. What I need is three columns each with different column names containing the data between the '~'..
For example:
Trading Status Problem1 Problem2
Trading Concession Telemetry - OCPD / Low Sales
I have a trawl around and found a few code examples that work but none will work within my view.
Many thanks in advance :) | you mean split the string at the delimiter ?
```
declare @a as varchar(100)
set @a='Trading~Concession~Telemetry - OCPD / Low Sales'
select substring(@a,0,patindex('%~%',@a)) as trading_status,reverse(substring(reverse(@a),0,PATINDEX('%~%',(reverse(@a))))) as problem1,
substring(@a,patindex('%~%',@a)+1,10) as problem2
```
# [DEMO](http://www.sqlfiddle.com/#!6/d41d8/17534)
Note:its not a dynamic solution but it works in your case | Try this:
```
select cast(c1 as nvarchar) + '~' + cast(c2 as nvarchar) + '~' + cast(c3 as nvarchar)
from table
``` | SQL breaking a string between characters in a view | [
"",
"sql",
"select",
""
] |
I have a simple table.
```
Date | Revenue
5/1 12
5/2 25
5/3 93
.
.
11/15 47
```
I am trying to write a query that returns two columns. The first column is Date, day-by-day, like the original table. The second column is 30-Day-Revenue, which is the sum of the "Revenue" column in the original table for the last 30 days, ending on the displayed date. There is a lot of overlap when we sum. Thanks in advance! | I have an alternative solution (assumes your table is called `revenue_table`):
```
SELECT a.Date, SUM(b.Revenue)
FROM revenue_table a, revenue_table b
WHERE b.Date <= a.Date AND b.Date > a.Date - 30
GROUP BY a.Date;
``` | ```
SELECT table1.Date, table1.Revenue, Past30DayRevenue = SUM(table2.Revenue)
FROM insert_your_table_name_here table1
JOIN insert_your_table_name_here table2 ON DATEDIFF(day, table2.Date, table1.Date) BETWEEN 0 AND 29
GROUP BY table1.Date, table1.Revenue
ORDER BY table1.Date;
``` | Sum of revenue everyday, for last 30 days on each day | [
"",
"sql",
""
] |
I need to filter based on a timestamp and would like to get everything within a certain day. The timestamps are like this: `02/06/2014 7:45:59 AM` or translated `2014-02-06 07:45:59`
```
select *
from P_FAR_SBXD.T_CLAIM_SERVICE_TYP_DIM
where service_type_id = 134469888 and valid_from_tsp not like '2014-02-06 %'
```
When I run this query, I am returned the error: `Partial String matching requires character operands`
Upon searching this error, I was given `The user used the partial string matching operator (LIKE) with an argument that was not a character string.`
So what can I use to match a date? **edit:** or in this case, not a date? | You should be able to just cast to a date and compare to your desired date, something like;
```
SELECT *
FROM P_FAR_SBXD.T_CLAIM_SERVICE_TYP_DIM
WHERE service_type_id = 134469888
AND CAST(valid_from_tsp AS DATE) = '2014-02-06'
```
EDIT: If you have a large table, this query will not use indexes well. If that is important, just do a range check between midnight and next midnight instead;
```
SELECT *
FROM P_FAR_SBXD.T_CLAIM_SERVICE_TYP_DIM
WHERE service_type_id = 134469888
AND valid_from_tsp >= '2014-02-06' AND valid_from_tsp < '2014-02-07'
``` | The following is a better way to express the date condition:
```
select *
from P_FAR_SBXD.T_CLAIM_SERVICE_TYP_DIM
where service_type_id = 134469888 and
valid_from_tsp >= DATE '2014-02-06' and
valid_from_tsp < DATE '2014-02-07';
```
or:
```
select *
from P_FAR_SBXD.T_CLAIM_SERVICE_TYP_DIM
where service_type_id = 134469888 and
valid_from_tsp >= DATE '2014-02-06' and
valid_from_tsp < DATE '2014-02-06' + interval '1' day;
```
The difference is important. In general, when you have a function on a column, the database does not use indexes. So these forms will use an index on the column. The best index for this query is `T_CLAIM_SERVICE_TYP_DIM(service_type_id, valid_from_tsp)`. | sql NOT LIKE syntax | [
"",
"sql",
"teradata",
""
] |
I have a `Emptbl` in which I have `EmpType` Column.
In EmpType I have following data for example :
```
E0123
M0123
E1245
E4578
M1245
E0478
M4789
E4762
```
Now I want to get only those emp data which have same `EmpType` for example below data:
```
E0123
M0123
E1245
M1245
```
And want to show this data as group by as `0123` and `1245`
So how to get above data? I use `UNION` but it does not get valida data.
Thanks | ```
Select A.*
From EmpTbl A
Inner Join
EmpTbl B
On SubString(A.EmpType, 2, 4) = SubString(B.EmpType, 2, 4) And
SubString(A.EmpType, 1, 1) <> SubString(B.EmpType , 1, 1)
``` | Try this:
```
select substring(emptype, 2, len(emptype))
from emptbl
group by substring(emptype, 2, len(emptype))
having count(*) > 1
```
The hard-coded 2 is based on your sample data. If instead you had an arbitrary number of letters before the numeric part, e.g. 'ABCDEFG0123', you could use `patindex` to get the starting index for your substring like so;
```
select substring(emptype, patindex('%[0-9]%',emptype), len(emptype)
``` | Get data from table using group by | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I've got a table `PERSON_PROPERTIES` that resembles the following :
```
| ID | KEY | VALUE | PERSON_ID |
| 1 | fname | robert | 1 |
| 2 | lname | redford | 1 |
| 3 | fname | robert | 2 |
| 4 | lname | de niro | 2 |
| 5 | fname | shawn | 3 |
| 6 | nname | redford | 3 |
```
I would like to `SELECT` (in JPQL or in PSQL) the `PERSON_ID` that matches the given `fname` and `lname`.
I've tried
```
`SELECT DISTINCT *
FROM PERSON_PROPERTIES t0
WHERE ((((t0.key = 'fname')
AND (t0.value = 'robert'))
AND ((t0.key = 'lname')
AND (t0.value = 'redford'))))`
```
but it returns me no value.
I've also tried
```
`SELECT DISTINCT *
FROM PERSON_PROPERTIES t0
WHERE ((((t0.key = 'fname')
AND (t0.value = 'robert'))
OR ((t0.key = 'lname')
AND (t0.value = 'redford'))))`
```
but this way it returns me all values. I don't know how to turn the query properly for it to give me only value `1`. | ```
SELECT PERSON_ID
FROM PERSON_PROPERTIES
group by PERSON_ID
having sum(case when key = 'fname' and value = 'robert' then 1 else 0 end) > 0
and sum(case when key = 'lname' and value = 'redford' then 1 else 0 end) > 0
```
Groupy by the person and select only those having both values. | Another approach would be with subselect (caution, it's MS SQL 2012)
```
SELECT PERSON_ID
FROM PERSON_PROPERTIES
WHERE [Key] = 'fname' AND value = 'robert'
AND PERSON_ID in
(SELECT PERSON_ID FROM PERSON_PROPERTIES WHERE [Key] = 'lname' AND value = 'redford')
```
[Fiddle Demo](http://sqlfiddle.com/#!6/74e0d/5) | SQL SELECT multiple keys/values | [
"",
"sql",
"jpql",
"psql",
""
] |
I have a simple table that has two columns `uid` and `isEnded`. A `uid` can occur multiple times in this table and can have the value `0` or `1`. The value `0` can only occur one time for each unique `uid`.
For example:
---
```
| uid | isEnded |
------------------
| 1 | 1 |
| 1 | 1 |
| 1 | 0 |
| 2 | 1 |
| 2 | 1 |
| 3 | 0 |
| 3 | 1 |
------------------
```
What I need is a query that selects all `uid`'s where all of its `isEnded` values are set to `1`.
So in the above example I should only get `uid` 2 back. Because the other two `uid`'s still have an `isEnded` set to `0`.
With what kind of query can I get such a result back? So only the `uid`s which don't have any `isEnded` values set to `0`. | Well, if all of the values should be `1` for the `uid`s you want to select, that also means that the minimum value will also be `1`:
```
SELECT uid
FROM table
GROUP BY uid
HAVING MIN(isEnded) = 1
``` | Try the below query:
```
SELECT DISTINCT uid
FROM #Tab
WHERE UID NOT IN
(SELECT uid FROM #tab WHERE isended = 0)
``` | Get all records that are ended | [
"",
"sql",
"sql-server",
""
] |
I have two tables:
```
tickets
ticket_updates
```
and i am trying to run a query where it shows data from the tickets table and `order by` the latest `datetime` in the `ticket_updates` table
```
SELECT * from tickets where status = 'Completed' order by ??? DESC LIMIT 0,50
```
`ticketnumber` in the `tickets` table matches `ticketnumber` in the `ticket_updates` table | ```
SELECT t.*
FROM tickets AS t
JOIN ticket_updates AS tu ON t.ticketnumber = tu.ticketnumber
WHERE status = 'Completed'
ORDER BY tu.datetime DESC LIMIT 50
```
Try this. | One approach is to summarize the `ticket_updates` table to get what you want:
```
select t.*
from tickets t join
(select ticketid, max(datetime) as max_datetime
from ticket_updates
group by ticketid
) tu
on t.ticketid = tu.max_datetime
order by tu.max_datetime desc
limit 0, 50;
``` | SQL Query selecting from two separate tables using a order clause | [
"",
"mysql",
"sql",
""
] |
I'm trying to do an update on my SQL DB (2008 R2), but for some reason it's updating more than I expected. I think there's an issue with my where, join, and update commands but I'm having trouble finding info on scope and order of operations. Fortunately, I'm practicing on DB backups that are restored before I make the change in the production one!
I've found [this](https://stackoverflow.com/questions/1293330/how-can-i-do-an-update-statement-with-join-in-sql) link that seems similar (join and update), but it's tough for me to apply it to my case.
For the testUnitCount of 15578, I'm trying to change the unitNo from 05101 to 05088. For some reason, it's moving the unitNo for all of them for this TestNumber. It's an OLAP DB (Cubes), so it may seem more complicated with all the tables than people are used to. I thought I had the command correct this time:
```
SELECT DashboardData.TestNumber, TestUnits.unitNo, TestUnitCounts.testUnitCount
FROM DashboardData INNER JOIN
TestUnitCounts ON DashboardData.TestUnitCountID = TestUnitCounts.testUnitCountID INNER JOIN
MeasurementData ON TestUnitCounts.testUnitCountID = MeasurementData.TestUnitCountID INNER JOIN
TestUnits ON DashboardData.TestUnitID = TestUnits.testUnitID AND TestUnitCounts.testUnitID = TestUnits.testUnitID AND
MeasurementData.TestUnitID = TestUnits.testUnitID
where unitNo='05101'
AND TestNumber='1024'
AND TestUnitCounts.testUnitCount='15578'
order by testUnitCount asc
UPDATE TestUnits
SET unitNo='05088' where unitNo='05101'
```
Does anyone know what the command needs to be changed to so I just change the testUnitCount of 15578 for unitNo 05101->05088 for Test 1024? Why is it changing all of them for that TestNumber?
Here is my CTE attempt for the same thing. I'm getting 0 row(s) affected when I execute it:
```
Use OLAP05132014C
GO
WITH QueryName_CTE (unitNo,TestNumber,testUnitCount)
AS
(
SELECT DashboardData.TestNumber, TestUnits.unitNo, TestUnitCounts.testUnitCount
FROM DashboardData INNER JOIN
TestUnitCounts ON DashboardData.TestUnitCountID = TestUnitCounts.testUnitCountID INNER JOIN
MeasurementData ON TestUnitCounts.testUnitCountID = MeasurementData.TestUnitCountID INNER JOIN
TestUnits ON DashboardData.TestUnitID = TestUnits.testUnitID AND TestUnitCounts.testUnitID = TestUnits.testUnitID AND
MeasurementData.TestUnitID = TestUnits.testUnitID
where unitNo='05101'
AND TestNumber='1024'
AND TestUnitCounts.testUnitCount='15578'
)
Update QueryName_CTE
SET unitNo='05088' where unitNo='05101'
``` | I thought I'd update this since we got it working. My co-worker used a different approach (worked) and I'm not exactly sure why it didn't work (directly) with the parameters given for the problem, and the other values had to be used, but this is what fixed it.
So the tables involved look like this:
```
PQdata table name ---------DashboardData table name----------TestUnits table name
key pqID key pqID key testUnitID
TestIndex TestIndex unitNo
TestNumber |
TestUnitID |
| |
TestUnitCounts table name------------
key testUnitCountID
testUnitID
testUnitCount
```
I went back and documented it based on his queries:
•He needed to look at it first:
```
SELECT PQdata.pqID, PQdata.TestIndex, TestUnits.unitNo, TestUnits.testUnitID, DashboardData.TestNumber, TestUnitCounts.testUnitCount
FROM DashboardData INNER JOIN
TestUnitCounts ON DashboardData.TestUnitCountID = TestUnitCounts.testUnitCountID INNER JOIN
TestUnits ON DashboardData.TestUnitID = TestUnits.testUnitID AND TestUnitCounts.testUnitID = TestUnits.testUnitID INNER JOIN
PQdata ON DashboardData.pqID = PQdata.pqID
where TestNumber='1024'
AND unitNo='05101'
AND testUnitCount='15578'
```
•This provided pqid corresponding to TestNumber: 10204
•Then he had to find testUnitID for unitNo 05088:
```
SELECT PQdata.pqID, PQdata.TestIndex, TestUnits.unitNo, TestUnits.testUnitID, DashboardData.TestNumber, TestUnitCounts.testUnitCount
FROM DashboardData INNER JOIN
TestUnitCounts ON DashboardData.TestUnitCountID = TestUnitCounts.testUnitCountID INNER JOIN
TestUnits ON DashboardData.TestUnitID = TestUnits.testUnitID AND TestUnitCounts.testUnitID = TestUnits.testUnitID INNER JOIN
PQdata ON DashboardData.pqID = PQdata.pqID
where TestNumber='1024'
AND unitNo='05088'
```
•Therefore need to change it to testUnitID: 2971
•Plus he had to find original testUnitID similarly: 2970
•Therefore, update needed looks like this:
```
UPDATE DashboardData SET testUnitID = 2971 WHERE testUnitID = 2970 AND pqID = 10204
```
It was a more round-about approach than I had tried (mine didn't work). | As stated in the comment above, the update is currently being run seperately. Change the query to be an update instead of a select.
Change your query to be -
```
UPDATE TestUnits
SET TestUnits.unitNo = '05088'
FROM DashboardData INNER JOIN
TestUnitCounts ON DashboardData.TestUnitCountID = TestUnitCounts.testUnitCountID INNER JOIN
MeasurementData ON TestUnitCounts.testUnitCountID = MeasurementData.TestUnitCountID INNER JOIN
TestUnits ON DashboardData.TestUnitID = TestUnits.testUnitID AND TestUnitCounts.testUnitID = TestUnits.testUnitID AND
MeasurementData.TestUnitID = TestUnits.testUnitID
where unitNo='05101'
AND TestNumber='1024'
AND TestUnitCounts.testUnitCount='15578'
order by testUnitCount asc
``` | SQL Update command getting more than expected | [
"",
"sql",
"sql-update",
""
] |
I'm looking for help with a formula. I'm looking for how to do two separate SELECT queries, but without merging them so.
```
SELECT basetype from table1 where name="test";
**SELECT itemid from table2 where itemid="5";**
```
I want the query to display basetype as a column and itemid as another column. Short version is two selects in one query displaying results. Data doesn't have to match between the tables.
EDIT: I screwed up. It's two separate tables. The results I want is basically this.
No union.
```
BASETYPE | ITEMID
1 | 5
``` | I suspect you want this:
```
select rn, max(basetype) as basetype, max(itemid) as itemid
from ((SELECT @rn := @rn + 1 as rn, basetype, NULL as itemid
from table1 cross join
(select @rn := 0) var
where name = 'test'
) union all
(SELECT @rn2 := @rn2 + 1, NULL, itemid
from table2 cross join
(select @rn2 := 0) var
where itemid = '5'
)
) t
group by rn;
``` | Try with union :
```
SELECT basetype from table1 where name="test"
union
SELECT itemid as basetype from table1 where itemid="5";
``` | mysql select two different queries | [
"",
"mysql",
"sql",
"select",
"scripting",
""
] |
I have a table metrics which has the following columns :
```
stage name
---------------------
new member
new member
old member
new visitor
old visitor
```
Now I can find out how many new or old members are there by running a query like this :
```
select stage, count(*) from metrics where name = 'member' group by stage;
```
This will give me the following result:
```
stage count
-----------
new 2
old 1
```
But along with this I want output like this :
```
total stage count
------------------
3 new 2
3 old 1
```
Total is sum of all rows statisfying where clause above. How do I need to modify my previous query to get the result I need? Thanks. | You can do something like this:
```
with t as
(select stage from metrics where name = 'member')
select
(select count(*) from t) as total,
stage, count(*)
from t
group by stage
```
Check it: <http://sqlfiddle.com/#!15/b97a4/9>
This is compact variant and includes the `'member'` constant only once. | The [window-function](http://www.postgresql.org/docs/9.3/static/tutorial-window.html) using variant:
```
with member as (
select stage, count(*)
from metrics where name = 'member'
group by stage
)
select sum(count) over () as total, member.*
from member
```
<http://sqlfiddle.com/#!15/b97a4/18> | Multi-level aggregation from a table | [
"",
"sql",
"postgresql",
""
] |
I am having duplicate rows with the same storeactivityid show up in my results...
This is the primary key, so this should not happen. Is there something wrong with my joins that could cause this? I could use distinct, but that will not solve the issue here.
Any tips or advice? There are 3 duplicates showing for each result!
```
select pd.storeactivityid,e.EMPLOYEENAME,c.ChainName,c.UserCode as ChainNumber,
s.storenumber,s.StoreNameAndNumber,
pd.startdatetime,
pd.enddatetime,
cast((datediff(s, pd.startdatetime, pd.enddatetime) / 3600.0) as decimal(9,2)) as duration,
exceptioncodes,pe.Description,isnull(pd.approved, 0) as approved,
isnull(pd.comment, '') as comment,
pd.modifieddate
from payrolldetail pd with (nolock)
inner join payperiods pp with (nolock) on pd.enddatetime between pp.begindate and pp.enddate and pp.CompanyID = @companyid
left join stores s with (nolock) on pd.storeid = s.storeid
left join chains c with (nolock) on c.chainid = s.chaincode
left join employees e with (nolock) on pd.employeeid = e.employeeid
inner join payrollexceptions pe with (nolock) on pd.ExceptionCodes = pe.Code
where pd.companyid = @companyid
and cast(getdate() as date) between pp.begindate and pp.enddate
and exceptioncodes = @exceptioncodes
and pd.companyid = @companyid
``` | If it is a primary key, you can be certain that in the actual table you do not have duplicate rows with the same `storeactivityid`.
Your query returns rows with the same `storeactivityid` because at least one of the joined tables has the matches the condition specified in the join.
My best guess it is due to the followoing join:
```
inner join payperiods pp with (nolock) on pd.enddatetime between pp.begindate and pp.enddate and pp.CompanyID = @companyid
```
Is it possible that a company has multiple `payrolldetails` within the same range of dates specified in the `payperiods` table? | i do not know what is in each of the tables,
but the easiest way i found to debug something like his is
```
select [storeactivityid],count([storeactivityid]) as [count]
from [<table>]
<Start adding joins in one at a time>
where [count] > 1
group by [storeactivityid]
``` | Duplicate rows in SQL Server | [
"",
"sql",
"sql-server",
"duplicates",
"rows",
""
] |
An event has many participants. A participant has a field of "status".
```
class Event < ActiveRecord::Base
has_many :participants
end
class Participant < ActiveRecord::Base
belongs_to :event
end
```
I need to find all events except the following ones: events where every one of its participants has a status of 'present'.
I can find all events where some of its participants have a status of 'present' with the following AR code:
```
Event.joins(:participants).where
.not(participants: {status: 'present'})
.select("events.id, count(*)")
.group("participants.event_id")
.having("count(*) > 0")
```
That creates SQL like:
```
SELECT events.id, participants.status as status, count(*)
FROM `events` INNER JOIN `participants`
ON `participants`.`event_id` = `events`.`id`
WHERE (`participants`.`status` != 'present')
GROUP BY participants.event_id HAVING count(*) > 0
```
This *almost* works. The problem is that if one of the participant's rows (within the scope of `@participant.event_id`) has a status of something other like "away", the event will still get fetched, because at least some of the sibling records are of a status equal to something other than "present".
I need to ensure that I am filtering out every event record with *all* participants of a status of "present".
I am open to ActiveRecord or SQL solutions. | If I get it right your problem can be classified as relational division. There are basically two ways to approach it:
1a) Forall x : p(x)
which in SQL has to be translated to:
1b) NOT Exists x : NOT p(x)
For your problem that would be something like:
```
SELECT e.*
FROM events e
WHERE NOT EXISTS (
SELECT 1
FROM PARTICIPANTS p
WHERE p.status <> 'present'
AND p.event_id = e.event_id
)
```
i.e. any given event where there does not exist a participant such that status != 'present'
The other principle way of doing it is to compare the number of participants with the number of participants with status present
```
SELECT e.id
FROM events e
JOIN participants p
ON p.event_id = e.id
GROUP BY e.event_id
HAVING count(*) = count( CASE WHEN p.status = 'present' then 1 end )
```
Both solutions are untested so there might be errors in there, but it should give you a start | I really like [Lennarts examples](https://stackoverflow.com/a/23707565/3453463)
I made a simple modification to the first example which will only return EVENT parent records which have Participation Child records, and is much faster at processing than finding the counts for each.
```
SELECT e.*
FROM events e
INNER JOIN participants p ON p.event_id = e.event_id
WHERE NOT EXISTS (
SELECT 1
FROM PARTICIPANTS p
WHERE p.status <> 'present'
AND p.event_id = e.event_id
)
GROUP BY e.event_id
``` | find all parent records where all child records have a given value (but not just some child records) | [
"",
"sql",
"ruby-on-rails",
"ruby-on-rails-4",
"has-many",
"belongs-to",
""
] |
Hey so I have a question.
I have two tables. table1 and table2.
table1:
```
id | car_numbers | type | model | type_id
1 3 bmw <model1> 1
2 5 bmw <model2> 1
3 2 mercedes <model1> 2
4 4 mercedes <model2> 2
5 1 chevrolet <model1> 3
```
table2:
```
id | price | type_id
1 100 1
2 200 1
3 300 2
4 400 2
5 500 3
```
What I want, is to display the 'type', the 'car\_numbers' and the average price of each car type. Basically the result of what I want between those two tables is:
```
type | car_numbers | average_price
bmw 8 150
mercedes 6 350
chevrolet 1 500
```
How can I do that? I know I have to relate to the type\_id that's common in both tables but how can I do that? | ```
SELECT type, car_numbers, AVG(price) AS average_price
FROM (SELECT type_id, type, SUM(car_numbers) AS car_numbers
FROM table1
GROUP BY type_id) AS t1
JOIN table2 AS t2 ON t1.type_id = t2.type_id
GROUP BY type
```
[DEMO](http://www.sqlfiddle.com/#!2/cbb37/3) | I think it might be this you are looking for
```
SELECT t.name, sum(Distinct o.car_number) car , avg(w.price) price FROM
TYPE t
INNER JOIN tone AS o ON o.type_id = t.id
INNER JOIN ttwo AS w ON w.type_id = t.id
GROUP BY t.name
```
<http://sqlfiddle.com/#!2/1937a/51> | MySQL relation between tables | [
"",
"mysql",
"sql",
"database",
""
] |
I have a table that has approximately 4 million records. I would like to make it have 240 million like so:
1. Add an additional column of type BIGINT,
2. Import 59 times the data I already have,
3. And for each 4 million group of records, have the additional column to have a different value
The value of the additional column would come from another table.
So I have these records (except that I have 4 millions of them and not just 3):
```
| id | value |
+----+-------+
| 1 | 123 |
| 2 | 456 |
| 3 | 789 |
```
And I want to achieve this (except that I want 60 copies and not just 3):
```
| id | value | data |
+----+-------+------+
| 1 | 123 | 1 |
| 2 | 456 | 1 |
| 3 | 789 | 1 |
| 4 | 123 | 2 |
| 5 | 456 | 2 |
| 6 | 789 | 2 |
| 7 | 123 | 3 |
| 8 | 456 | 3 |
| 9 | 789 | 3 |
```
I tried to export my data (using `SELECT .. INTO OUTFILE ...`), then re-import it (using `LOAD DATA INFILE ...`) but it is really painfully slow.
Is there a fast way to do this?
Thank you! | Sounds like you'd like to take the `cartesian product` of 2 tables and create a new table since you say `The value of the additional column would come from another table`? If so, something like this should work:
```
create table yourtable (id int, value int);
create table yournewtable (id int, value int, data int);
create table anothertable (data int);
insert into yourtable values (1, 123), (2, 456), (3, 789);
insert into anothertable values (1), (2), (3);
insert into yournewtable
select t.id, t.value, a.data
from yourtable t, anothertable a
```
* [SQL Fiddle Demo](http://sqlfiddle.com/#!3/525bf6/1)
Results:
```
ID VALUE DATA
1 123 1
2 456 1
3 789 1
1 123 2
2 456 2
3 789 2
1 123 3
2 456 3
3 789 3
```
---
Edit, Side Note -- it looks like your ID field in your new table is not suppose to keep repeating the same ids? If so, you can use an `AUTO_INCREMENT` field instead. However, this could mess up the original rows if they aren't sequential. | First, I would recommend that you create a new table. You can do this using a `cross join`:
```
create table WayBigTable as
select t.*, n
from table t cross join
(select 1 as n union all select 2 union all select 3 union all select 4 union all select 5 union all
. . .
select 60
) n;
```
I'm not sure why you would want a `bigint` for this column. If you really need that, you can cast to `unsigned`. | Duplicate records of a MySQL table | [
"",
"mysql",
"sql",
""
] |
I keep looking at this and do not understand why I am not getting a result set back here are my my queries
```
SELECT UserID FROM @SelectedID
SELECT UserID FROM @SelectedIdValue
SELECT UserID FROM @SelectedID WHERE NOT EXISTS (SELECT UserID FROM @SelectedIdValue
```
And here is the result set returned

As you can see 194 does not exist in the second result set so why am I not getting 194 returned? Am I using `NOT EXISTS` wrong here? | You need a correlated subquery:
```
SELECT UserID
FROM @SelectedID si
WHERE NOT EXISTS (SELECT 1
FROM @SelectedIdValue siv
WHERE si.UserId = siv.UserId
);
```
Your version of the query simply returned false for all rows. The subquery returns a value, so something exists.
EDIT:
You can phrase this as a `left outer join` if you want:
```
SELECT si.UserID
FROM @SelectedID si LEFT OUTER JOIN
@SelectedIdValue siv
ON si.UserId = siv.UserId
WHERE siv.UserId IS NULL;
``` | The exists subquery only checks whether user ids exist, not what their value is. If you replace "not exists" with "UserID not in" your query will return the expected result. Note though that "in" doesn't work as expected when there are null values in the column, verify if that's possible before using "in". | Something is Wrong with my SQL Query NOT EXISTS | [
"",
"sql",
"sql-server",
""
] |
Using SQL Server Management Studio 2012, I'm trying to create a copy of a local database. I found a few variants of solution. One of them - backup and restore database as new one - [HERE](http://msdn.microsoft.com/en-us/library/ms190447%28v=SQL.100%29.aspx).
Currently create database backup with name `Rewards2_bak`. This copy of file place in to system catalog `C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Backup\`

Next step - create query for restoring database as copy of existing one
```
GO
use master
RESTORE FILELISTONLY
FROM Rewards2_bak
RESTORE DATABASE Rewards2_Copy
FROM Rewards2_bak
WITH RECOVERY,
MOVE 'Rewards2_data' TO 'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\Rewards2_copy.mdf',
MOVE 'Rewards2_log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\Rewards2_log_copy.ldf'
GO
```
Got error, that I don't have a backup device `Rewads2_backup`. I'm right understand that in this case like device i can use file, and also file location? Think something missing...
For creating backup use next query (all OK)
```
USE Rewards2;
GO
BACKUP DATABASE Rewards2
TO DISK = 'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Backup\Rewards2_bak.bak'
WITH FORMAT,
MEDIANAME = 'SQLServerBackups',
NAME = 'Full Backup of Rewards2';
GO
```
Also try to use tools in SQL Server 2012 `Task --> Backup` and `Task --> Restore`, but got error - can't create backup. (Launched program with Administrator rights)
This is screen how I config restore to copy

But I have error, that I can't overwrite database file `Rewards2`. And this is question - why it wants to overwrite `Rewards2` if I put new name of database `Rewards2_copy`. Or I understand something wrong?

Shure, that ther is a few more possible variants for making copy of database, but really whant to find problem for this solution. Where i make mistake/ what I forget or don't understand. | When you restore a database from a backup it will use the same file names as the original database.
You need to change these file names during the restore.
On the restore window go to the `Files` tab. On this window you have a column called `Restore As`.
Change the file names at the end of the path in the column Restore As for each of the files you see. | I think you are trying to overwrite the logical filenames from the database you are trying to copy...guessing a bit but try this - try it in SSMS if you don't need to script it right now:
1. Backup the database you want to copy (Rewards2\_bak.bak is fine)
2. Create a new database (Rewards2\_copy)
3. Restore into Rewards2\_copy using Rewards2\_bak.bak
Remember in point three to change the logical filenames within the options tab - otherwise you will try and overwrite the Rewards2 files.
There are lots of guides around:
* [Copy Database with Backup and Restore](http://technet.microsoft.com/en-us/library/ms190436.aspx)
* [Copy Database to other servers](http://msdn.microsoft.com/en-us/library/ms189624.aspx)
* [How do you backup and restore a database as a copy on the same server?](https://stackoverflow.com/questions/1360529/how-do-you-backup-and-restore-a-database-as-a-copy-on-the-same-server)
Via SQL to determine the logical filenames you can use: filelistonly
```
restore filelistonly from disk='enter backup file path here'
```
Then use the filenames reported to build you restore query, as you have already tried | How to create copy of database using backup and restore | [
"",
"sql",
"sql-server",
"database",
"copy",
"ms-query",
""
] |
I am unsure if my terminology is correct. I have this query:
```
select (select count(*)
from table1
where column1 = 'x' and column2 = 'y' and column3 = 'z'
) as new_column1,
(select count(*)
from table 1
where column1 = 'x' and column2 = 'y' and column3 = 'z'
) as new_column2;
```
I would like to find the percentage difference between the two new (aggregate?) columns. The original columns are varchar(2),two varchar(4) columns, and a varchar(3) column. | This will give you the delta between sum1 and sum2, expressed as a percentage relative to sum2:
```
select sum1 = s.sum1 ,
sum2 = s.sum2 ,
delta = sum1 - sum2 ,
delta_pct = 100.0 * ( sum1 - sum2 ) / sum2
from ( select sum1 = sum(case when t.c1='a' and t.c2='b' and t.c3='c' then 1 else 0 end) ,
sum2 = sum(case when t.c1='x' and t.c2='y' and t.c3='z' then 1 else 0 end)
from table1 t
) s
```
using the *derived table* in the from clause makes for cleaner, more readable SQL as you're not duplicating the aggregation expressions all over the place. | Here's one way you could do it:
```
select
new_column1,
new_,
new_column1 / new_ * 100 as PercentDiff
from
(
select (select count(*)
from table1
where column1 = 'x' and column2 = 'y' and column3 = 'z'
) as new_column1,
(select count(*)
from table1
where column1 = 'x' and column2 = 'y' and column3 = 'z'
) as new_
)
``` | SQL Percent difference between 2 aggregate columns | [
"",
"sql",
"sql-server-2008",
""
] |
I have a table `messages` and a table `deleted_messages` every time the delete action on a message is fired instead delete the record I create a new record on the `deleted_messages` table. Then i would like retrieve the messages without the deleted messages on the `deleted_messages`.
**ps**: I don't use soft delete here because a lots of users can delete the messages for they self but not for the others users
My schema:
**users table**
```
id | name
```
**messages table**
```
id | user_id | message
```
**deleted\_messages**
```
id | message_id | user_id
```
The query that i'm trying to perform to get all messages of the user 1 without the deleted messages is the following but it return 0 rows:
```
select *
from messages
left join deleted_messages on deleted_messages.message_id = messages.id
where deleted_messages.user_id != 1
```
Take a look [SQLFiddle](http://sqlfiddle.com/#!2/1c2e3/2) it should get 2 messages but it return null. | You can do so
```
select *
from messages m
left join deleted_messages d on d.message_id = m.id
where
d.message_id IS NULL
AND m.user_id = 1
```
This will give all the messages from user 1 which are not deleted
## [Demo](http://sqlfiddle.com/#!2/1c2e3/14)
Other way to use `NOT EXISTS`
```
select *
from messages m
where not exists
(select 1 from deleted_messages d where d.message_id = m.id)
AND m.user_id = 1
```
## [Demo](http://sqlfiddle.com/#!2/1c2e3/24)
For performance factor you can find the details here
[**LEFT JOIN / IS NULL vs. NOT IN vs. NOT EXISTS: nullable columns**](http://planet.mysql.com/entry/?id=24888) | add the were condition in the left join clause
```
select *
from messages
left join deleted_messages on deleted_messages.message_id = messages.id
and deleted_messages.user_id = 1
where deleted_messages.message_id is null
```
[sqlFiddle](http://sqlfiddle.com/#!2/1c2e3/17) | select rows mysql where the value of the left join is different | [
"",
"mysql",
"sql",
""
] |
How can I get list of tables which have rows in my database.
```
Select A.Name
From Sys.Tables A
-- Inner Join with ?
-- Or What conditions ?
```
Is it possible?
please guide me!
Thank you. | This query will help.
```
SELECT obj.name TableName, st.row_count
FROM sys.dm_db_partition_stats(nolock) st
inner join sys.objects(nolock) obj on st.object_id = obj.object_id
WHERE index_id < 2 and st.row_count > 1 and obj.type = 'u'
```
Edited to show user tables only. | Well you could get the list of tables from INFORMATION\_SCHEMA.TABLES and then cursor through each table and exec some dynamic sql to get the COUNT(\*) for each table. So yes, it is possible, but I don't know if there is a more simpler solution. | How to get list of tables which have rows? | [
"",
"sql",
"sql-server",
""
] |
I want to perform a select using an index (number) of a column. I tried:
```
select 1 from "user"
select '1' from "user"
```
but they don't do what I expect. | You cannot do this in postgres. Selecting a literal (such as `1` or `'1'`) would just return its value. The only place such indices are allowed is in the `order by` clause, and even there, they don't relate to the order of columns in the table, but in the select list:
```
SELECT col1, col2, col3
FROM my_table
ORDER BY 1
```
EDIT:
One caveat is using `order by <some index>` in conjunction with `select *`, which may seem as though the index related to the order of columns in the table. However, the `*` is first expanded to contain all columns, and only then is the `order by` clause applied. So ultimately, it does refer to the `select` list and not to the actual structure of the table.
EDIT2:
As @klin mentioned, postgres' `group by` clause also allows indices:
```
SELECT col1, COUNT(*)
FROM my_table
GROUP BY 1
``` | When i need the FIRST column (and i don't know the column name) , i do something like this:
```
SELECT uno FROM _your_table_ as t(uno);
```
Just use an alias for table and columns!..
if you REALLY NEED the NUMBER 1 you could write something like this:
```
SELECT "1" FROM _your_table_ as t("1");
```
double quotes... ugly, but works!!!! | Refer to a column by its number (index) | [
"",
"sql",
"postgresql",
"select",
"postgresql-9.2",
""
] |
I have a table T1, which contains which contains columns (A , B, C ,D) in which A is PK.
And I have some more tables. And I want to get some data from these tables.
I get the data as per my sql query from these tables.
Sql query (query1) is as follows
```
select t3.col1 as A, t3.col4 as F, t4.col as H
from t3, t4
where t3.col1 = t4.col2;
```
Now
I want to get data from Table T1 and above query1 result.
```
select B , C , D , F, H
from T1, Temp
where t1.A = Temp.A;
```
where Temp is the above sql query1 result.
How I can achieve this?
Any suggestions. | I'd suggest using explicit join as in:
```
select t1.B, t1.C, ..., t3.col1 as A, t3.col4 as F, t4.col as H
from t3
join t4
on t3.col1 = t4.col2
join t1
on t1.A = t3.col1;
``` | try this
```
SELECT t1.B as B, t1.C as B, t1.D as D, t3.col4 as F, t4.col as H
FROM t1, t3, t4
WHERE t1.A=t3.col1 AND t3.col1=t4.col2
``` | SQL Query, Get data from multiple tables and query result | [
"",
"mysql",
"sql",
""
] |
I am just starting with mySQL, and have been through many of the tutorials, but there are a couple of things I cannot find.
**1:** Do you just include the following in your HTML, or would it go into a different file (if so, what would the extension be)?
```
CREATE DATABASE user_db;
CREATE TABLE Users
(
UserNum int,
LastName varchar(100),
FirstName varchar(100),
Address varchar(255),
City varchar(255),
ZipCode varchar(100),
Phone int,
MonthBorn varchar(100),
DayBorn int,
YearBorn int
);
```
**2:** How would you create a database used by every page of your website, and never gets deleted (ex. for a user database)? | You can't use mySQL with only HTML. You need to use a server-side scripting language (such as PHP) to do your database work. As for the second question, a database runs on a server where it can be accessed by any page (that is given permission to access it). And the data would persist (never get deleted until you delete it). That's what a database is designed to do. Check out some tutorials on the Google to get a handle on databases. | If you wish to use a database in your web application, then you need to set up and configure the database, in this case. MySQL would be running and you would use commands like that to create the tables within the database. From there, pending on the language(s) your using, you have a plethora of options available for access.
Pretty good guide for using Active Records with Ruby on Rails:
<http://guides.rubyonrails.org/active_record_basics.html>
Asp.Net has tons of options but works better with SQL Server versus mySQL:
<http://www.asp.net/web-forms/tutorials/data-access>
You can't interact with a database directly with just html. You'll need to use something like PHP, Ruby, C#, or even javascript on Nodejs to interact with the database. If you wish to do user authentication and management, I suggest starting with a CMS (Content Management System) like WordPress or DotNetNuke. They have plenty of starting out tutorials on how to set up your database, connecting to it and handle user authentication in a fairly secure manner. | Proper way to Include SQL | [
"",
"mysql",
"sql",
""
] |
I need to Find out the course with the most passes from my table tblResults.
```
tblResults:
StuID Course Symbol
1001 CSC101 P
1001 RNG101 F
1002 CSC101 P
1002 RNF101 F
1003 HAP101 P
1004 HAP101 P
```
i.e should give CSC101 (And all other courses (HAP101) with the same ammount of passes)
I have tried:
```
CREATE VIEW Part1 AS
SELECT NumbF
FROM
(SELECT COUNT(Course) AS NumbP,
Course
FROM tblResults
WHERE Symbol = 'P')
GROUP BY Course);
CREATE VIEW Part2 AS
SELECT MAX(NumbP) AS Maxnum
FROM Part1,
tblResults
WHERE Symbol = 'P'
GROUP BY Course;
SELECT Part1.Course
FROM Part1,
Part2
WHERE Part1.NumbP = Part2.MaxNum
```
But I seem to be doing something incorrectly. Please help | Something like this should work:
```
create view yourview as
select course, count(*) passcnt
from tblResults
where symbol = 'P'
group by course
select *
from yourview
where passcnt = (select max(passcnt) from yourview)
```
* [SQL Fiddle Demo](http://sqlfiddle.com/#!2/d377d4/1)
Note, you don't need the view, I just left it for simplicity. | ```
SELECT Course, count(StuID) count
FROM tblResults
GROUP BY Course
HAVING count = (SELECT max(c)
FROM (SELECT count(StuID) c, Course
FROM tblResults
GROUP BY Course
WHERE Symbol = 'p'
) counts
);
``` | SQL Comparing 2 values that must be determined | [
"",
"mysql",
"sql",
""
] |
Im currently amending the opencart search feature, this is a simplified version of the code without the PHP, Im looking to order my results by the most matched words. I have looked at other questions but cant seem to grasp how to use `CASE` in SQL to simply prioritise my matches.
Is it possible someone could show me the syntax
```
SELECT id from oc_products where
product_description LIKE '%my search keywords%'
OR product_description LIKE '%my%'
OR product_description LIKE '%search%'
OR product_description LIKE '%keywords%'
ORDER BY
CASE
WHEN product_description LIKE '%my search keywords%'
WHEN product_description LIKE '%my search&'
WHEN product_description LIKE '%my&'
WHEN product_description LIKE '%search&'
WHEN product_description LIKE '%keywords&',
ASC
```
Im aware that my syntax is totally off but Im not sure how to implement `THEN` within that code to allow for prioritizing my results in the above order.
Thank you | ***First solution :*** `CASE`
```
SELECT id
FROM oc_products
WHERE product_description LIKE '%my search keywords%'
OR product_description LIKE '%my%'
OR product_description LIKE '%search%'
OR product_description LIKE '%keywords%'
ORDER BY CASE WHEN product_description LIKE '%my search keywords%' THEN 0
WHEN product_description LIKE '%my search&' THEN 1
WHEN product_description LIKE '%my&' THEN 2
WHEN product_description LIKE '%search&' THEN 3
WHEN product_description LIKE '%keywords&' THEN 4
END DESC
```
***Second solution :*** listing conditions in `ORDER BY`
```
SELECT id
FROM oc_products
WHERE product_description LIKE '%my search keywords%'
OR product_description LIKE '%my%'
OR product_description LIKE '%search%'
OR product_description LIKE '%keywords%'
ORDER BY product_description LIKE '%my search keywords%' DESC
, product_description LIKE '%my search&' DESC
, product_description LIKE '%my&' DESC
, product_description LIKE '%search&' DESC
, product_description LIKE '%keywords&' DESC
``` | ```
SELECT id
FROM oc_products
WHERE product_description LIKE '%my search keywords%'
OR product_description LIKE '%my%'
OR product_description LIKE '%search%'
OR product_description LIKE '%keywords%'
ORDER BY product_description LIKE '%my search keywords%' desc
, product_description LIKE '%my search%' desc
, product_description LIKE '%my%' desc
, product_description LIKE '%search%' desc
, product_description LIKE '%keywords%' desc;
```
SQL fiddle here: <http://www.sqlfiddle.com/#!2/8b043/4> | Syntax for SQL on how to order by best match with most words using CASE | [
"",
"mysql",
"sql",
"search",
""
] |
I'm trying to get only the rows that are in USD and EUR from a table with more currencies.
I thought the code should be something like:
```
SELECT IF(CONTRACTS_IN_DIFFERENT_CURRENCIES.CURRENCY='USD',1,0) OR IF(CONTRACTS_IN_DIFFERENT_CURRENCIES.CURRENCY='EUR',1,0
FROM CONTRACTS_IN_DIFFERENT_CURRENCIES
```
But I know this is not how it should be. I would like the table to be something like a column of USD and EUR | The preceding answers are good in my opinion, but let's say you would have alot of currencies, you could do
```
SELECT * FROM CONTRACTS_IN_DIFFERENT_CURRENCIES WHERE CURRENCY IN ("USD","EUR")
``` | It looks as though you're trying to use Excel's `IF(condition, true_response, false_response)` syntax. The equivalent in T-SQL is the `CASE WHEN THEN ELSE END` syntax:
```
SELECT
CASE
WHEN CONTRACTS_IN_DIFFERENT_CURRENCIES.CURRENCY ='USD' THEN 1
WHEN CONTRACTS_IN_DIFFERENT_CURRENCIES.CURRENCY='EUR' THEN 1
ELSE 0
END
FROM
CONTRACTS_IN_DIFFERENT_CURRENCIES
```
This will work with more complex queries than the example you're giving us. Another way of doing it, if you have a number of possible values for the same field that will return the same response, would be
```
SELECT
CASE
WHEN CONTRACTS_IN_DIFFERENT_CURRENCIES.CURRENCY IN ('USD','EUR') THEN 1
ELSE 0
END
FROM
CONTRACTS_IN_DIFFERENT_CURRENCIES
```
However, that is not the right syntax to use to get just the rows with certain currencies; the previous answer with
```
SELECT *
FROM
CONTRACTS_IN_DIFFERENT_CURRENCIES
WHERE
CONTRACTS_IN_DIFFERENT_CURRENCIES.CURRENCY IN ('USD','EUR')
```
would work best for that. | Simple If Else statement in sql | [
"",
"mysql",
"sql",
"if-statement",
""
] |
I have two tables with following data:
`Test_parent`:
```
parent_id title
------------------
1 Parent1
2 Parent2
3 Parent3
4 Parent4
```
`Test_child`:
```
child_id parent_id property
------------------------------------
1 1 A
2 2 A
3 2 B
4 3 A
5 3 C
6 4 A
```
I want to select all rows from table test\_parent where parent contains children with (BOTH) properties A and B (so this would be record with parent\_id=2)
This is the best solution I wrote so far:
```
select *
from test_parent p
where (select COUNT(property)
from test_child c
where p.parent_id = c.parent_id and c.property in ('A', 'B')) = 2
```
Is there any more "correct" way?
Many thanks!
This is full script for objects:
```
CREATE TABLE [dbo].[test_parent](
[parent_id] [int] IDENTITY(1,1) NOT NULL,
[title] [nvarchar](50) NOT NULL,
CONSTRAINT [PK_test_parent] PRIMARY KEY CLUSTERED
([parent_id]))
GO
CREATE TABLE [dbo].[test_child](
[child_id] [int] IDENTITY(1,1) NOT NULL,
[parent_id] [int] NOT NULL,
[property] [nvarchar](10) NOT NULL,
CONSTRAINT [PK_test_child] PRIMARY KEY CLUSTERED
([child_id]))
GO
ALTER TABLE [dbo].[test_child] WITH CHECK ADD CONSTRAINT [FK_test_child_test_child] FOREIGN KEY([parent_id])
REFERENCES [dbo].[test_parent] ([parent_id])
GO
ALTER TABLE [dbo].[test_child] CHECK CONSTRAINT [FK_test_child_test_child]
GO
SET IDENTITY_INSERT [dbo].[test_parent] ON;
INSERT INTO [dbo].[test_parent]([parent_id], [title])
SELECT 1, N'Parent1' UNION ALL
SELECT 2, N'Parent2' UNION ALL
SELECT 3, N'Parent3' UNION ALL
SELECT 4, N'Parent4'
SET IDENTITY_INSERT [dbo].[test_parent] OFF;
GO
SET IDENTITY_INSERT [dbo].[test_child] ON;
INSERT INTO [dbo].[test_child]([child_id], [parent_id], [property])
SELECT 1, 1, N'A' UNION ALL
SELECT 2, 2, N'A' UNION ALL
SELECT 3, 2, N'B' UNION ALL
SELECT 4, 3, N'A' UNION ALL
SELECT 5, 3, N'C' UNION ALL
SELECT 6, 4, N'A'
GO
SET IDENTITY_INSERT [dbo].[test_child] OFF;
``` | I'm not sure about "more correct", but a simple JOIN with GROUP BY/HAVING will do it without a subquery;
```
SELECT test_parent.parent_id, test_parent.title
FROM test_parent
JOIN test_child ON test_child.parent_id=test_parent.parent_id
AND test_child.property IN ('A','B')
GROUP BY test_parent.parent_id, test_parent.title
HAVING COUNT(DISTINCT test_child.property)=2
```
[An SQLfiddle to test with](http://sqlfiddle.com/#!3/2c3de/4).
It will basically join the parent with any child that has a property equal to 'A' or 'B', group by the parent row and count the distinct values of `property` on the child. If it's equal to 2 ('A' and 'B' being the two possible values), return the parent. | The query in the question
```
select *
from test_parent p
where 2 = (select COUNT(property)
from test_child c
where p.parent_id = c.parent_id
and c.property in ('A', 'B'))
```
has a little problem: if there are two child, both with 'A' or both with 'B' the parent will show in the resultset, an that's different from the requirement stated.
It will also not show the parent with more than two child, even if they have only 'A' and 'B' as property, for example if we add the rows
```
child_id | parent_id | property
7 | 5 | A
8 | 5 | B
9 | 5 | A
```
to the data of test\_child the parent 5 will not be in the resultset (stated that 5 is in the parent table)
Another way to write the query of Joachim Isaksson is to move the check on the child properties to the `HAVING` clause
```
SELECT tp.id, tp.title
FROM test_parent tp
INNER JOIN test_child tc ON tp.parent_id = tc.parent_id
GROUP BY tp.id, tp.title
HAVING COUNT(DISTINCT tp.property) = 2
AND SUM(CASE WHEN tp.property IN ('A', 'B') THEN 0 ELSE 1 END) = 0
``` | SQL - child must contain all specified values | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have a table that looks like this:
```
location | object | date-time-string | id
--------------------------------------------
Login | label | 5/17/14 4:29:20 | 1
Login | main | 5/17/14 4:29:20 | 2
Login | button | 5/17/14 4:29:20 | 3
Login | name | 5/17/14 4:29:20 | 4
Login | passwd | 5/17/14 4:29:20 | 5
Login | pic | 5/17/14 4:29:20 | 6
Login | label | 5/16/14 1:13:10 | 7
Login | main | 5/16/14 1:13:10 | 8
Login | button2| 5/16/14 1:13:10 | 9
```
I have this query:
```
select object from table where location = 'Login' order by time desc
```
I want to get a list of all the items in the 'object' column that are from the most recent time. The date-time-string is generated from `DateTime.Now` in C# and inserted into the sql table.
How do you return items using a SQL command that are the most recent based on a date time string? | 1. Use a datetime field for dates. Really. No excuses.
2. Use [ISO-8601](http://xkcd.com/1179/) to represent date-time as string. No excuses.
If you are wrong on either of the above (as you are, inexcusable), then cast the string to a date time and sort by the casted value. In your case is `mm/dd/yy` which is [style 1](http://msdn.microsoft.com/en-us/library/ms187928.aspx)
```
select object
from table
where location = 'Login'
order by CONVERT(datetime, [date-time-string], 1), desc;
```
The performance will be abysmal, but you well deserve that for breaking all that is good and sound about handling dates. | I'm not 100% sure , but try this:
```
SELECT object
FROM table a
INNER JOIN
(SELECT TOP 1 date-time-string
FROM table
ORDER BY date-time-string DESC) b
ON a.date-time-string=b.date-time-string
``` | How do you return items using a SQL command that are the most recent based on a date time string? | [
"",
"sql",
"sql-server-2012",
""
] |
I have a syntax that can copy all records from tables that have the same fields:
```
INSERT INTO table2 SELECT * FROM table1 WHERE id = '7'
```
So I would like to know how do I keep copying all values except the 'id' field (because him is primary key and auto increment). | You list the columns:
```
insert into table2(col1, . . . coln)
select col1, . . ., coln
from table1
where id = '7';
```
Under most circumstances, you should list the columns explicitly. You can run into problems even when tables have the same columns but in a different order.
(The one exception in code that I would write is in a script where `table1` is created from `table2` using `create table as`.) | You have to list all the columns specifically:
```
INSERT INTO table2 (col1, col2, col3, ...)
SELECT col1, col2, col3, ...
FROM table1
WHERE id = '7'
``` | Copy all records between tables with the exception of a line | [
"",
"mysql",
"sql",
""
] |
Follow my code
```
begin
declare @Iorder int
set @Iorder=0
declare @no int
set @no=(select MAX(IOrder) from Team)
if @no=NULL
set @Iorder=1
else
begin
set @Iorder=(select MAX(IOrder) from Team)
set @Iorder=@Iorder+1
end
end
```
if in Team table has no row `select MAX(IOrder) from Team` statement return `NULL` value so statement `if @no=NULL` is not correct because `@no` is `int` type then SQL Server return a error `Null value is eliminated by an aggregate or other SET operation.`
So how to fix it? | Test using `is null` instead.
```
begin
declare @Iorder int
set @Iorder=0
declare @no int
set @no=(select MAX(IOrder) from Team)
if @no is null
set @Iorder=1
else
begin
set @Iorder=(select MAX(IOrder) from Team)
set @Iorder=@Iorder+1
end
end
```
Your code can be rewritten using `isnull()` instead.
```
declare @Iorder int
select @Iorder = 1 + isnull(max(IOrder), 0) from Team
``` | You can simply do this all in a short form.
Try this:
```
begin
declare @Iorder int
SELECT @Iorder = ISNULL(MAX(IOrder),0)+1 FROM Team
end
```
**Explanation:**
`@Iorder` will be 1 (i.e., 0+1) if `MAX(IOrder)` is NULL.
Otherwise, `@Iorder` will be `MAX(IOrder)+1`. | how to assign NULL type for int type in sql server | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
Imagine I have a table like this one:
```
CREATE TABLE marcas
(
id_marca integer,
marca character varying
));
```
I would like to make a query but get the value in every field empty.
I know that could solve it like this:
`SELECT '' as id, '' as marca FROM marcas`
The problem is that i have plenty of tables and some of them have more than 100 fields...
I need a SQL statement that could get all the row fields of a table but empty and in an easy way... | Here is one method to get `NULL` in every column. It uses `left outer join` with a failing condition:
```
select t.*
from (select 1 as val
) v left outer join
table t
on 1 = 0;
```
EDIT:
If you want to do this in Access, that is a challenge. The expression `select 1 as val` doesn't work. The following should:
```
select t.*
from (select max(1) as val
from table as t
) as v left outer join
table as t
on val = 0;
```
This should also work in Postgres, but it has unnecessary overhead. | if you just want the column list and no rows returned then
```
SELECT TOP 0 * FROM marcas
``` | SQL Empty query results | [
"",
"sql",
"database",
"select",
""
] |
```
select a.name from student a, student b
where a.id = b.id and a.id = 1;
```
vs
```
select a.name from student a
inner join student b
on a.id = b.id and a.id = 1;
```
Are they actually the same? | They are the same as far as the query engine is concerned.
The first type, commonly called a comma join, is an implicit inner join in most (all?) RDBMSs. The syntax is from ANSI SQL 89 and earlier.
The syntax of the second join, called an explicit inner join, was introduced in ANSI SQL 92. It is considered improved syntax because even with complex queries containing dozens of tables it is easy to see the difference between join conditions and filters in the where clause.
The ANSI 92 syntax also allows the query engine to potentially optimize better. If you use a something in the join condition, then it happens before (or as) the join is done. If the field is indexed, you can get some benefit since the query engine will know to not bother with certain rows in the table, whereas if you put it in the `WHERE` clause, the query engine will need to join the tables completely and then filter out results. *Usually* the RDBMS will treat them identically -- probably 999 cases out of 1000 -- but not always.
See also:
[Why isn't SQL ANSI-92 standard better adopted over ANSI-89?](https://stackoverflow.com/questions/334201/why-isnt-sql-ansi-92-standard-better-adopted-over-ansi-89) | Obviously they are not the same syntactically, but they are semantically (they return the same). However, I'd write the second one as:
```
select a.name from student a
inner join student b on a.id = b.id
where a.id = 1;
``` | What is the difference between these two SQL? | [
"",
"sql",
"join",
""
] |
**For Example:** I have a table called Trans. There are three columns: `Date`, `Customer`, `Sales`:
```
Date Customer Sales
01/05/14 1 1000
02/05/14 2 5000
03/05/14 3 2500
10/05/14 4 10000
01/12/13 1 25000
02/12/13 2 500
06/12/13 3 1000
31/12/13 4 3000
```
I would like to display Customer sales by date as:
```
Customer Sales_2013 Sale_2014
1 25000 1000
2 500 5000
3 1000 2500
4 3000 10000
```
I have tried my level best and still trying :-(
any assistance would be greatly appreciated.
Thanks in anticipation. | For `SQL Server` something like the below will work, the approach should work for any `TSQL`, may just need to alter the `CASE WHEN` for different `RDMS`. Note that you will need to change your field name `Date` to something else or you will inevitably run into problems.
```
SELECT Customer,
sum(CASE WHEN datepart(year, Date) = 2013 THEN Sales ELSE 0 END)
As Sales_2013,
sum(CASE WHEN datepart(year, Date) = 2014 THEN Sales ELSE 0 END)
As Sales_2014
FROM Trans
GROUP BY Customer
```
**EDIT**
And because you learn something new every day here would be the `PIVOT` approach, which I know works in `SQL Server 2005`, don't know about anything else:
```
SELECT *
FROM
(
SELECT datepart(year,Date) As SlsYear,Customer,Sales
FROM Trans
) As Source
PIVOT
(
sum(Sales)
FOR SlsYear IN ([2013],[2014])
) As Pvt
```
Forgive me if this is not quite correct, just learnt about `PIVOT` now...
**EDIT for Separate Tables as per Comment**
You should be able to do this by simply using a `UNION ALL` query.
```
SELECT *
FROM
(
SELECT datepart(year,Date) As SlsYear,Customer,Sales
FROM tbl2013Sales
UNION ALL
SELECT datepart(year,Date) As SlsYear,Customer,Sales
FROM tbl2014Sales
) As Source
PIVOT
(
sum(Sales)
FOR SlsYear IN ([2013],[2014])
) As Pvt
``` | Assuming you are using Sql Server, you can use following query
```
select a.id,
(select sum(sales) from salesData where datepart(year,Date)=2013 and id=a.id) as sales_2013,
(select sum(sales) from salesData where datepart(year,Date)=2014 and id=a.id) as sales_2014
from salesData as a
group by a.id
```
Sql fiddle
<http://sqlfiddle.com/#!3/18d98/3/0> | How to select same column of values with different date criterias and display as column1 and column2 in the same query | [
"",
"sql",
"sql-server-2008",
""
] |
I have a table (see the image below --red box). It describes the content of my table (A, B, C, and D) are the columns. The data structure will always be like this, if col A is Type\_1, only col B has a content while if Col A is Type\_2, Col C and D has contents while col B is NULL.
Now, the table which re enclosed with green box is my desired output.

My experience on building a select statement is not very extensive and I'm almost leaning towards creating two separate tables to get my desired result (like 1 table for Type\_1 data only and another table for Type\_2 data only).
Question is, is it possible to query two rows and combine it to become a single output result using SELECT query? Considering that these two rows are on the same table?
Thanks. | Something like this:
```
SELECT
Table2Id,
MAX(B) B,
MAX(C) C,
MAX(D) D
FROM tbl
WHERE A != 'Type_3'
GROUP BY Table2Id
``` | Assuming that there is only one row of data for type1 and one row of data for type 2, you can use the following:
```
SELECT Id, MAX(B) AS B, MAX(C) AS C, MAX(D) AS D
FROM Table2
WHERE A IN ('Type_1','Type_2')
GROUP BY Id
```
Example in this [SQL Fiddle](http://sqlfiddle.com/#!6/e3551/1/0) | SQL Query combine two rows into one row of data | [
"",
"sql",
"sql-server",
""
] |
Edit 1: I am trying to fetch using this below query but problem is that the end div is not taken the occurrence after the start Point i.e
```
select ID, post_title, substr(post_content,instr(post_content,'<div style="position:absolute') + 0, instr(post_content,'</div>')) as temp from wp_posts where post_content LIKE '%mySpamFilter Text%' LIMIT 10
```
One of my Blog has been attacked by spammers, I have around 100+ posts which have the unwanted links or messages which was fused by spammers. I want to know how can I replace the string between two strings.
```
Start string = '<div style="position:absolute;'
End String = '</div>' (This End div should be the first end div after the above Start string)
```
I tried all the options which is available on Stack overflow but no luck so far. Please advice whats the best approach to go ahead. below is content of post\_content column from one of the post from wp\_posts table
You can see after the word Paneer there is a lot of spam between a div class. I want to get rid of this from my database. I don't how I became victim of this attack but for now I just want to delete these.
```
<p>Hey Foodies,</p>
<p>Biryani, the pride of Hyderabad, is definitely one dish which everyone knows to cook in their very own ways and styles. Biryani is one such thing which totally distinguishes itself with the plain rice we eat daily and the regular pulao. Biryani is the BIRYANI. So, lets look into the detailed procedure of the much loved Hyderabadi delicacy, the vegetarian version. Oh yes, this is the Hyderabadi Dum Veg Biryani!</p>
<p>This recipe would take 380-400 grams of uncooked Basmati rice which would serve 6.</p>
<div class="easyrecipe">
<link itemprop="image" href="http://mywebsite.in/wp-content/uploads/2013/09/Biryani-300x225.jpg">
<div class="item ERName">Hyderabadi Veg Dum Biryani</div>
<div class="ERClear"></div>
<div class="ERHead"><span class="xlate">Recipe Type</span>: <span class="type">Main Course</span></div>
<div class="ERHead">Cuisine: <span class="cuisine">Indian</span></div>
<div class="ERHead">Prep time: <time itemprop="prepTime" datetime="PT30M">30 mins</time></div>
<div class="ERHead">Cook time: <time itemprop="cookTime" datetime="PT1H15M">1 hour 15 mins</time></div>
<div class="ERHead">Total time: <time itemprop="totalTime" datetime="PT1H45M">1 hour 45 mins</time></div>
<div class="ERHead">Serves: <span class="yield">6</span></div>
<div class="ERIngredients">
<div class="ERIngredientsHeader">Ingredients</div>
<ul class="ingredients">
<li class="ingredient">For Vegetables: Carrot - 1 medium</li>
<li class="ingredient">Potatoes - 1 medium</li>
<li class="ingredient">Paneer ***<div style="position:absolute; left:-3905px; top:-3984px;">Gloves fast it <a href="http://www.goprorestoration.com/natural-viagra-foods">natural viagra foods</a> recently! Like as <a href="http://www.backrentals.com/shap/daily-cialis.html">daily cialis</a> the purchase 1 pad <a href="http://www.vermontvocals.org/buy-online-cialis.php">generic viagra cheap</a> and matte easy <a href="http://www.teddyromano.com/blue-pills/">blue pills</a> me many. Content but <a href="http://augustasapartments.com/qhio/10-mg-cialis">10 mg cialis</a> the as the helps Amazon <a href="http://www.mordellgardens.com/saha/cheap-viagra-canada.html">http://www.mordellgardens.com/saha/cheap-viagra-canada.html</a> . And baths etc would. I've <a href="http://www.teddyromano.com/brand-cialis/">brand cialis</a> Appears dollars hands still <a href="http://www.backrentals.com/shap/generic-cialis-europe.html">shop</a> October a smell <a href="http://www.hilobereans.com/buy-real-viagra/">http://www.hilobereans.com/buy-real-viagra/</a> in have. Of better <a href="http://www.creativetours-morocco.com/fers/herbal-viagra-australia.html">cheap generic cialis</a> it smelled to and <a rel="nofollow" href="http://www.goprorestoration.com/best-price-viagra">best price viagra</a> t customer anything been <a href="http://www.mordellgardens.com/saha/viagra-online-reviews.html">viagra online reviews</a> 5 supply time <a href="http://www.hilobereans.com/viagra-canada-pharmacy/">"here"</a> the product what <a href="http://www.vermontvocals.org/ed-supplements.php">buy levitra</a> biological by cream!</div>*** - 1/2 cup</li>
<li class="ingredient">Cauliflower - 1/2 cup</li>
<li class="ingredient">Green peas - 1 tbsp.</li>
<li class="ingredient">Yogurt - 1/2 cup</li>
<li class="ingredient">Mint - 1 tbsp.</li>
<li class="ingredient">Coriander - 1 tbsp.</li>
<li class="ingredient">Ginger-Garlic paste - 1 tsp.</li>
<li class="ingredient">Green chili - 4 to 5</li>
<li class="ingredient">Oil - 2 tbsp</li>
<li class="ingredient">Salt - As per taste</li>
<li class="ingredient">Biryani Masala - 1 and 1/2 tbsp.</li>
<li class="ingredient">Red Chili Powder - 1/2 tsp.</li>
<li class="ingredient">Garam Masala Powder - 1/4 tsp.</li>
<li class="ingredient">Whole Garam Masala - Custom or readymade</li>
<li class="ingredient">For Rice: Basmati Rice(soaked for 1 hour) - 380 gms</li>
<li class="ingredient">Water - 6-8 cups</li>
<li class="ingredient">Oil - 1-2 Tbsp.</li>
<li class="ingredient">Whole Garam masala - Custom or readymade</li>
<li class="ingredient">Salt - 3 Tsp.</li>
<li class="ingredient">For Dum(Bringing together): Yogurt - 1/2 cup</li>
<li class="ingredient">Saffron strands - dipped in milk, a few</li>
<li class="ingredient">Chopped Nuts - As desired</li>
<li class="ingredient">Mint and Coriander - two handfuls</li>
<li class="ingredient">Fried onions - two handfuls</li>
<li class="ingredient">Green chili - 4-5 slits</li>
<li class="ingredient">Water - 1/4 cup</li>
</ul>
</div>
<div class="ERInstructions">
<div class="ERInstructionsHeader">Instructions</div>
<div class="instructions">
<ol>
<li class="instruction">For Veggies: In a kadhai add oil. Now add whole garam masala, ginger-garlic paste. Saute for a minute. Now add carrot, potatoes, cauliflower, peas and salt. Saute until they are lightly cooked.</li>
<li class="instruction">After the veggies are a bit cooked, add in biryani masala, red chili powder, garam masala powder and gradually add yogurt stirring well to prevent curdling of curd.</li>
<li class="instruction">Now add mint, coriander, paneer. Cook until the moisture gets dried out which was caused due to adding yogurt. This would take approx 5 minutes. Veggies should not be cooked completely as we will dum it later on. It should 70% cooked.</li>
<li class="instruction">After the moisture is dried, add some fried onions and transfer to a bowl.</li>
<li class="instruction">For Rice: Boil water. Add oil, whole garam masala, salt. Boil until roaring boil. Add the soaked rice. In about 3-4 minutes in high flame rice will be 70% done. Test by eating some if it has a bite but its tastes like cooked or press between ur fingers. If breaks into 2 parts its ready. Strain it and spread on a big plate.</li>
<li class="instruction">For Dum: Take a cooker, add half of the vegetables, yogurt, green chilli, a pinch of salt and some nuts. Let it heat. Now add a handful of mint coriander. Now top it off with a good layer of rice.</li>
<li class="instruction">Next add the remaining vegetables, remaining mint-coriander(leave 1 tsp. for top), fried onions and the rice. Spread the rice and add the saffron mixture with a bit of mint-coriander, fried onion.</li>
<li class="instruction">Now sprinkle 1/4 cup of water over it, Cover and cook for 2 minutes in lowest flame.</li>
<li class="instruction">Transfer the cooker to a big pot with some water. This water bath prevents the dum to get burnt.. In about 30-35 minutes the Biryani is ready to make you dig into it.</li>
</ol>
</div>
</div>
<div class="ERNutrition"></div>
<div>
<div class="ERNotesHeader">Notes</div>
<div class="ERNotes">Cut vegetables in a uniform size.[br]Veggies are less, but the rice is used more for Biryanis.[br]You could use raw chopped nuts or saute them in oil and add.[br]Make sure to soak rice for atleast 1 hour.</div>
</div>
<div class="endeasyrecipe" style="display: none;">3.2.1255</div>
</div>
<p> </p>
<p><a href="http://mywebsite.in.cp-25.webhostbox.net/wp-content/uploads/2013/09/Biryani-2.jpg"><img class=" wp-image-411 alignright" alt="Biryani-2" src="http://mywebsite.in.cp-25.webhostbox.net/wp-content/uploads/2013/09/Biryani-2.jpg" width="189" height="142"></a></p>
<p>Recipe Ingredients are lengthy.. But it looks only onscreen.. Once you start preparing them they does not seem long or more.. Basic Ingredients, Easy Recipe and Traditional Hyderabadi Taste.. Dont forget to try it, I am sure you'll love it and make it again and again!!!</p>
<p><a href="http://www.youtube.com/mywebsite" target="_blank">Do Subscribe on YouTube</a></p>
<p><a href="http://www.fb.com/mywebsite" target="_blank">Like us on FB</a></p>
<p> </p>
<p>Video Recipe:</p>
<p><iframe src="//www.youtube.com/embed/zf0_AJfp5AA" height="500" width="835" allowfullscreen="" frameborder="0"></iframe></p>
``` | Your query is close, but you need to use LOCATE as well as INSTR to find the end of the embedded string:
```
select
ID,
post_title,
substr(post_content,
instr(post_content,'<div style="position:absolute'),
LOCATE('</div>',post_content,instr(post_content,'<div style="position:absolute')+30)-instr(post_content,'<div style="position:absolute')
+6) as temp
from wp_posts
where post_content LIKE '%<div style="position:absolute%'
LIMIT 10
```
See example here: <http://sqlfiddle.com/#!2/d0cf2f/13> | the answer is variation of the following:
```
update wp_posts
set post_content = CONCAT(LEFT(post_content, LOCATE('div style=', post_content)-1),
SUBSTRING(post_content, LOCATE('</div>', post_content)+7))
where LOCATE('div style=', post_content) > 0
```
Changing the "div style" to whatever beginning that works. | MYSQL Replace string between two known strings | [
"",
"mysql",
"sql",
"phpmyadmin",
""
] |
I want to load some datas from DB, and i have a problem i don't understand.
My function :
```
public List<News> getNews(){
db = this.getReadableDatabase();
List<News> tmp_list = new LinkedList<News>();
txtRequest = "SELECT * FROM myTable ";
Cursor c = db.rawQuery(txtRequest, null);
tmp_list = loadListNews(c);
return tmp_list;
}
```
After that, I call to the function "loadListNews" :
```
public List<News> loadListNews(Cursor c) {
List<News> tmp_list = new LinkedList<News>();
while(c.moveToNext()) {
tmp_list.add(loadOneNews(c));
}
return tmp_list;
}
```
And finally, I call this function to create my object news :
```
public News loadOneNews(Cursor c1) {
c1.moveToFirst();
// i'm creating my object
c1.close();
return tmpNews;
}
```
And with that, i have the error "Error to reopen an alreay closed object".. | You are closing the cursor after the first pass in your while loop.
Plus you are always moving to the first element of your SQL result thus potentially only reading the 1st one and creating an infinite loop. Luckily you have a close to stop your loop ;)
You could make the following small changes to improve it a little bit already:
```
public List<News> loadListNews(Cursor c) {
List<News> tmp_list = new LinkedList<News>();
c.moveToFirst()
while(c.moveToNext()) {
tmp_list.add(loadOneNews(c));
}
c.close()
return tmp_list;
}
public News loadOneNews(Cursor c1) {
// i'm creating my object
return tmpNews;
}
``` | Close cursor after using, not in while loop execution (on loadListNews).
```
public List<News> loadListNews(Cursor c) {
List<News> tmp_list = new LinkedList<News>();
while(c.moveToNext()) {
tmp_list.add(loadOneNews(c));
}
c.close();
return tmp_list;
}
``` | Android Error to reopen an alreay closed object | [
"",
"android",
"sql",
""
] |
Maybe the title of the question is not completly right. I will try explain better my issue.
I have two tables with following structure:
TABLE01:
```
ID | GENUS | SPECIES | INDIVIDUUM
1 | A | a | alfa
2 | B | b | beta
3 | C | c | gama
4 | D | d | delta
5 | E | e | epsilon
```
TABLE02:
```
ID1 | ID2 | INDEX
1 | 2 | 21%
1 | 3 | 17%
1 | 4 | 32%
1 | 5 | 43%
2 | 1 | 21%
2 | 3 | 19%
2 | 4 | 94%
2 | 5 | 91%
. . .
. . .
. . .
5 | 1 | 43%
5 | 2 | 91%
5 | 3 | 83%
5 | 4 | 76%
```
Than I do following select:
```
SELECT id FROM table01 WHERE individuum in (alfa,epsilon);
```
and receives following result:
```
| ID |
| 1 |
| 5 |
```
With that I do another select:
```
SELECT * FROM table02 WHERE ID1 in (1,5);
```
This time I receive, as you probably already know, the following result:
RESULT02:
```
ID1 | ID2 | INDEX
1 | 2 | 21%
1 | 3 | 17%
1 | 4 | 32%
1 | 5 | 43%
5 | 1 | 43%
5 | 2 | 91%
5 | 3 | 83%
5 | 4 | 76%
```
Now I would like to create a new table based on this results that would give me the following fields (and values):
```
id | individuum | species | genus | id2 | individuum2 | species2 | genus2 | index |
1 | alfa | a | A | 2 | beta | b | B | 21% |
1 | alfa | a | A | 3 | gama | c | C | 17% |
1 | alfa | a | A | 4 | delta | d | D | 32% |
1 | alfa | a | A | 5 | epsilon | e | E | 43% |
5 | epsilon | e | E | 1 | alfa | a | A | 43% |
5 | epsilon | e | E | 2 | beta | b | B | 91% |
5 | epsilon | e | E | 3 | gama | c | C | 83% |
5 | epsilon | e | E | 4 | delta | d | D | 76% |
```
It presents the data from the first table in an 'analytic' way that are somehow connected just like RESULT02 shows us in a 'synthetic' way.
I though in something like the following, but I am not sure that it is right.
```
SELECT
b.id1,
(SELECT a.individuum FROM table01 a WHERE id = a.id1) individuum,
(SELECT a.species FROM table01 a WHERE id = a.id1) species,
(SELECT a.genus FROM table01 a WHERE id = a.id1) genus,
b.id2,
(SELECT a.individuum FROM table01 a WHERE id = a.id2) individuum2,
(SELECT a.species FROM table01 a WHERE id = a.id2) species2,
(SELECT a.genus FROM table01 a WHERE id = a.id2) genus2,
b.index
FROM
table02 b
WHERE
individuum in (alfa , epsilon);
ORDER BY index DESC";
```
I would appreciate your help to create a better, faster and more efficient query. | try to see if this helps:
```
SELECT
table01.id,
table01.individuum,
table01.species,
table01.genus,
-- -----------------
table02.id as id2,
-- -----------------
t01.individuum as individuum2
t01.species as species2,
t01.genus as genus2,
-- -----------------
table02.index
from
table01
inner join
table02 on table01.ID = table02.ID1
left join
table01 as t01 on t01.ID = table02.ID2
where
table01.individuum in (alfa , epsilon)
order by
index DESC;
``` | Try this way. Just rename (with aliases) the fields.
```
select
t2.id, spec1.individuum, spec1.species, spec1.genus,
t2.id2, spec2.individuum, spec2.species, spec2.genus
t2.INDEX
from
table2 t2
table1 spec1,
table2 spec2
where t2.id1 = spec1.id
and t2.id2 = spec2.id
```
Then you can add whatever condition you want like yours own `spec1.individuum in ('alfa','epsilon')` or `t2.id in (1,5)` | How to present a mixed result of two tables using subqueries in MySQL? | [
"",
"mysql",
"sql",
""
] |
Table Position:
```
CREATE TABLE Position(
p# NUMBER(8) NOT NULL, /* Position number */
ptitle VARCHAR(30) NOT NULL, /* Position title */
employer VARCHAR(100) NOT NULL, /* Institution name */
salary NUMBER(9,2) NOT NULL, /* Salary */
extras VARCHAR(50) , /* Extras */
specification LONG , /* Specification */
CONSTRAINT Position_pkey PRIMARY KEY ( p# ),
CONSTRAINT Position_fkey1 FOREIGN KEY ( ptitle )
REFERENCES LPTitle ( title ) );
INSERT INTO Position VALUES ( 00000001, 'LECTURER', 'UNSW', 45000.00, 'computer', 'Teaching');
INSERT INTO Position VALUES ( 00000002, 'LECTURER', 'UOW', 45000.00, 'mouse pad', 'Research');
INSERT INTO Position VALUES ( 00000003, 'SENIOR LECTURER', 'UTS', 50000.00, NULL, 'A lot of hard work' );
INSERT INTO Position VALUES ( 00000004, 'ASSOC. PROFESSOR', 'UOW', 60000.00, NULL, NULL);
INSERT INTO Position VALUES ( 00000005, 'PROFESSOR', 'UQ', 80000.00, 'chair', 'Research' );
INSERT INTO Position VALUES ( 00000006, 'PROFESSOR', 'UNSW', 80000.00, 'chair', 'Research' );
INSERT INTO Position VALUES ( 00000007, 'PROFESSOR', 'UOW', 80000.00, 'chair', 'Teaching and research');
```
I'm trying to find the title of the positions with the largest salary. In this case it should be 'PROFESSOR'. This is the query I came out with:
```
SELECT DISTINCT
ptitle
FROM
Position
WHERE
NOT EXISTS
(
SELECT ptitle FROM Position WHERE salary < (SELECT MAX(salary) FROM Position)
)
;
```
The result I get is 'no rows selected'. When I run just the sub-query I can get all the position titles except for the highest salary position:
```
SQL> SELECT ptitle FROM Position WHERE salary < (SELECT MAX(salary) FROM Position);
PTITLE
------------------------------
LECTURER
LECTURER
SENIOR LECTURER
ASSOC. PROFESSOR
```
But whenever I run it as a sub-query in the NOT EXISTS query above I could not get back the position with highest salary. Why? | Your subquery:
```
SELECT ptitle FROM Position WHERE salary < (SELECT MAX(salary) FROM Position)
```
always finds the same four rows, so at least one result is always returned, so `exists` would always be true, so `not exists` is always false. You have no correlation between the row you're examining and the subquery. If you do want a `not exists` then you need to include the row from the main table in the subquery:
```
SELECT DISTINCT
ptitle
FROM
Position pos1
WHERE
NOT EXISTS
(
SELECT ptitle FROM Position pos2 WHERE pos2.salary > pos1.salary
)
;
```
To use `max` you could check equality instead:
```
SELECT DISTINCT
ptitle
FROM
Position
WHERE
salary = (SELECT MAX(salary) FROM Position)
;
```
[SQL Fiddle](http://sqlfiddle.com/#!4/14688/2).
Or use an analytic function so you don't have to hit the table twice, as suggested elsewhere. | An easier way to get the result you're looking for is to use an analytic function to `rank` all positions by salaries, and then just take the top one:
```
SELECT ptitle
FROM (SELECT ptitle, RANK() OVER (ORDER BY salary DESC) AS rk
FROM position)
WHERE rk = 1
``` | Queries as SELECT statements with NOT EXISTS clauses | [
"",
"sql",
"database",
"oracle11g",
"sqlplus",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.