Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I am not really sure what I am doing wrong, but it is Monday so this is expected. I am trying to process some data in a table. Occasionally, one of the columns will contain a question mark. I would like to replace all question marks to NULL.
This is my query, but it seems to just replace every single entry.
```
Updat... | I would rewrite this query to not use a `REPLACE`
```
UPDATE Table SET [Hours] = NULL WHERE [Hours] = '?'
```
EDIT: As for the reason your original query didn't work, as AlexK and roryap say, [The docs for `REPLACE` say that:](http://technet.microsoft.com/en-us/library/ms186862.aspx)
> Returns NULL if any one of the... | Use a `where` clause;
```
Update Table set [Hours] = NULL
where [Hours] like '%?%'
``` | Update Replace query is replacing every entry in the column? | [
"",
"sql",
""
] |
Given that I have a table `messages`
```
sender_id recipient_id
========== =============
1 2
1 3
2 1
```
Whats the most optimal query to get records in which one value is 1 and the other 2, i.e for the above example dataset, it should return both (1,2) and (2,1). Currently I am u... | If the sender can't also be the recipient:
```
select * from messages
where sender_id in (1, 2)
and recipient_id in (1, 2)
```
If it's possible to be both, add another filter:
```
select * from messages
where sender_id in (1, 2)
and recipient_id in (1, 2)
and sender_id != recipient_id
``` | The most straightforward approach seems to me to be to use `IN`:
```
select *
from messages
where (sender_id, recipient_id) in ((1, 2), (2, 1));
```
Testing on SQL Fiddle shows that it is sometimes faster than Bohemian's answer, and sometimes slower, depending on the data present. But for readability, I think this is... | Optimal query to find both (x,y) and (y,x) records | [
"",
"sql",
"postgresql",
""
] |
I have a table like this
The first table is the "Appointments" table with 'doctor\_id' the second table is the "Doctors" table also with 'doctor\_id'. The duplicate values from the appointments table represents how many appointment each doctor has. for example the doctor\_id(50) has 6 appointments.
```
doctor_id(Appo... | Assuming `doctor_id` is unique in the `doctors` table...
```
SELECT d.doctor_id AS doctor_id
, COUNT(a.doctor_id) AS appointment_count
FROM doctors d
LEFT
JOIN appointments a
ON a.doctor_id = d.doctor_id
GROUP BY d.doctor_id
```
To get the count by doctor\_id, you need to `GROUP BY` the doctor\... | ```
SELECT d.doctor_id, COUNT(a.doctor_id) FROM doctors d
Join appointment a
d.doctor_id =a.doctor_id
WHERE d.doctor_id > 50
GROUP BY a.doctor_id
```
try this code and hope this works. I am grouping the doctors appointments by the id | How to join Count(*) columns with another column in Mysql | [
"",
"mysql",
"sql",
"count",
""
] |
```
select COALESCE([ItemSlotX],0) as [ItemSlotX],COALESCE([ItemSlotY], 0 ) as [ItemSlotY] from [PowerUP_Items] where [ItemIndex]=16 and [ItemGroup]=255
```
In my case, is no record.
How can I return 0 for ItemSlotX and 0 for ItemSlotY if there is no record found? | If you want the results, even when there is no matching row, use this:
```
select COALESCE([ItemSlotX],0) as [ItemSlotX],COALESCE([ItemSlotY], 0 ) as [ItemSlotY]
from (select null dummy ) d
left
outer
join [PowerUP_Items]
on [ItemIndex]=16 and [ItemGroup]=255
``` | This?
```
select ItemSlotX, ItemSlotY from PowerUP_Items where ItemIndex=16 and ItemGroup=255
if @@rowcount = 0
select 0 as ItemSlotX, 0 as ItemSlotY
```
Or more general approach:
```
if exists (select * from PowerUP_Items where ItemIndex=16 and ItemGroup=255)
select ItemSlotX, ItemSlotY from PowerUP_Items w... | MSSQL Return 0 for null blank | [
"",
"sql",
"sql-server",
""
] |
To begin, yes this is for homework, and I've been trying to read and understand. Nothing has just said why one is better or worse. Anyway, in SQL Server using the Adventureworks data base, the following 3 queries are run:
```
USE AdventureWorks2012;
GO
--1
SELECT LastName
FROM Person.Person
WHERE LastName = 'Smith... | Open the phone book that is sorted by last names
1. Lookup for all "Smith"s
2. Lookup for all people whose last name starts with "Sm"
3. Lookup for all people whose last name ends with "mith"
Do you see now? | Keys in an index are sorted so that finding a value is easier. For string-type values they are sorted alphabetically (ascending or descending). That makes it easy to locate any value based on the whole value or its begininng.
The problem with matching on anything at the start (`'%mith'`) is that SQL Server cannot use ... | Why exactly is there a difference between performance? | [
"",
"sql",
"sql-server",
"performance",
"t-sql",
""
] |
I have an MS-SQL table, with a column titled 'ImportCount'.
Data in this column follows the below format:
```
ImportCount
[Schedules] 1376 schedule items imported from location H:\FOLDERA\AA\XX...
[Schedules] 10201 schedule items imported from location H:\FOLDERZZ\PERS\YY...
[Schedules] 999 schedule items imported f... | ```
select SUBSTRING(ImportCount,13,patindex('% schedule items%',ImportCount)-13) from table name
``` | Try
```
select left(ImportCount, patindex('%[^0-9]%', ImportCount+'.') - 1)
``` | MS-SQL - Extracting numerical portion of a string | [
"",
"sql",
"sql-server",
""
] |
I'm struggling to figure out the best way to write this query to use less queries if possible.. I'm wondering if a pivot table might be the correct way?
My 3 separate queries:
```
SELECT
ISNULL(SUM(ps.UnitsSold), 0) AS UnitsSold,
ISNULL(pg.[Description], 'Other') AS [Description]
FROM dbo.ProductSales ps
LEFT OUTER J... | i've changed your query a little to show a different technique which will combine your 3 queries. I may not have the brackets quite right round the SUMS but that gives you an idea. There are also better ways to do the sort of "date between" stuff you are trying, but that wasn't the question! See if that helps
```
SELE... | Do this with one query and conditional aggregation:
```
SELECT coalesce(pg.[Description], 'Other') AS [Description],
sum(case when ps.OrderDate BETWEEN GETDATE() - 10 AND GETDATE() - 3 then UnitsSold
end) as ThisWeek
sum(case when ps.OrderDate BETWEEN GETDATE() - 17 AND GETDATE() - 10 then Uni... | Multiple sql queries in one result | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
```
**Friends Table**
-------------------------
id seller_id buyer_id
-------------------------
1 101 102
2 102 104
3 103 101
4 104 101
**Name Table**
--------------
id name_id
--------------
101 Robin
102 Goblin
103 Ork
104 Wizard
```
... | You can do two times `JOIN` to achieve that :
```
SELECT
f.id
, n1.name_id As seller
, n2.name_id As buyer
FROM Friends f
INNER JOIN Name n1 ON n1.id = f.seller_id
INNER JOIN Name n2 ON n2.id = f.buyer_id
``` | ```
select f.id,n.name_id as "seller_id",nb.name_id as "buyer_id"
from [Friends Table] f
join [Name Table] n on n.seller_id=f.id
join [Name Table] nb on nb.buyer_id=f.id
``` | how to query for the 2 id's field whose value present in the same table B | [
"",
"sql",
"sqlite",
""
] |
I want to write a query in oracle sql, which returns every minute of the current day in one column. But i've got no idea, how to start :-(
```
min
27.03.2014 00:00
27.03.2014 00:01
27.03.2014 00:02
...
27.03.2014 23:59
```
Thanks | We can use arithmetic to manipulate dates, and the simple CONNECT BY trick to generate a stream of rows.
```
alter session set nls_date_format='dd-mon-yyyy hh24:mi'
/
with cte as ( select trunc(sysdate) as start_date from dual )
select start_date + ((level-1)/(24*60)) as date_w_mins
from cte
connect by level <= (24*6... | You can use `numtodsinterval` function and is simple too:
```
SELECT to_char(TRUNC(sysdate)+
numtodsinterval (level-1,'minute'),'dd.mm.yyyy hh24:mi') min
FROM dual
CONNECT BY LEVEL <= (24*60);
``` | Oracle query with every minute a day | [
"",
"sql",
"oracle",
"date-arithmetic",
""
] |
This query currently shows max(hella) so far
```
SELECT max(hella)
FROM (
SELECT G.firstname, G.lastname, count(*) as hella
FROM guest G, Timeslot TS, shows H
where G.timeslotnum = TS.timeslotnum
AND TS.shownumber = H.shownumber
AND H.showname = 'Fitness'
Group by g.firstname, G.lastname
ORDER by hella
)
As blabla
```... | This is much like what @maniek or @zfus already posted: returns a single row, arbitrary pick if there are ties.
But with proper JOIN syntax and shorter with some syntax candy:
```
SELECT g.firstname, g.lastname, count(*) AS hella
FROM guest g
JOIN timeslot t USING (timeslotnum)
JOIN shows s USING (shownumb... | ```
SELECT G.firstname, G.lastname, count(*) as hella
FROM guest G, Timeslot TS, shows H
where G.timeslotnum = TS.timeslotnum
AND TS.shownumber = H.shownumber
AND H.showname = 'Fitness'
Group by g.firstname, G.lastname
ORDER by hella desc
limit 1
``` | SQL Display info with Max(count(*)) | [
"",
"sql",
"postgresql",
"max",
"greatest-n-per-group",
""
] |
```
$a='asfda'; $b='sdgdfgd'; $c='sdfdsfg'; $d='sgdfgdsfg';
mysql_query("INSERT INTO `users`(`id`, `confirmation`, `name`, `email`, `password`) VALUES ('','$a','$b','$c','$d')");
```
i have 10 more column in my user table that i want to leave empty while one of them is 'cityID' (foreign key), its keep giving me this ... | Its because you've created an index in users table which is references to `id` field in `cities` table. Remove that index and you'll get rid of this error.
I suggested that you remove the index because your index seems to be of no help otherwise when you have foreign key index, you have to make you that an entry for f... | ```
mysql_query("set foreign_key_checks=0");
mysql_query("INSERT INTO `users`(`id`, `confirmation`, `name`, `email`, `password`) VALUES ('','$a','$b','$c','$d')");
``` | Cannot add or update a child row... why did i get this error? | [
"",
"mysql",
"sql",
""
] |
I have this code in crystal reports that gives me last week date range based on the current date.
First day of the week:
```
If DayOfWeek(currentdate) = 2 Then
currentdate
Else If DayOfWeek(currentdate) = 3 Then
dateadd ("d",-1,currentdate)
Else If DayOfWeek(currentdate) = 4 Then
dateadd ("d",-2,currentdate)
Else If ... | I generated some spaced out dates in the `parms` CTE then `SELECT` the `CurrentDate` from `parms`, the Sunday of the week prior to `CurrentDate` and the Saturday of the week prior to `CurrentDate`. I'm assuming that you want the dtate range to be Sunday - Saturday.
> Sunday - Saturday Ranges
```
;WITH parms (CurrentD... | This solution is tested and works. I am getting the previous week's Monday and Sunday as upper and lower bounds.
```
SELECT
-- 17530101 or 1753-01-01 is the minimum date in SQL Server
DATEADD(dd, ((DATEDIFF(dd, '17530101', GETDATE()) / 7) * 7) - 7, '17530101') AS [LowerLimit], -- Last Week's Monday
DATEADD... | How to get last week date range based on current date in sql? | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have an attendance table like this in MySQL
> EmpID | EventTime
>
> 90010 | 2014-03-05 06:50:30
>
> 90010 | 2014-03-05 06:50:45
>
> 90010 | 2014-03-05 06:51:02
>
> 90020 | 2014-03-05 06:52:50
>
> 90030 | 2014-03-05 06:55:47
The employee with ID '90010' is submitted more than 1 attendance data on March 5th.
Now, i w... | From your query, assuming you already have foreign keys on your MST\_Attendance table, you can just do a query on that table, since you have the two columns EmpID and EventTime there. You need to group by EmpID to obtain the minimum time:
```
SELECT EmpID, MIN(EventTime) as attendancetime
FROM MST_Attendance
WHERE DAT... | using `MIN` of EventTiem with `GROUP BY` will help you get the desired result
```
SELECT b.EmpID, MIN(a.EventTime) AS EventTime
FROM MST_Attendance a, MST_Employee b
WHERE a.EmpID=b.EmpID
AND DATE(a.EventTime)='2014-03-05'
GROUP BY b.EmpID;
``` | Get minimum time on same date in MySQL | [
"",
"mysql",
"sql",
"database",
""
] |
Please see the SQL DDL below:
```
create table dbo.Test(id int, name varchar(30))
INSERT INTO Test values (1, 'Mark')
INSERT INTO Test values (2,'Williams')
```
I am trying to return: 'Mark Williams' using an SQL SELECT. I have tried using an SQL Pivot, but it has not worked. | Possibly more flexible than COALESCE would be to use the STUFF and FOR XML pattern:
```
SELECT TOP 1
STUFF((SELECT ' ' + Name AS [text()]
FROM dbo.Test
ORDER BY id
FOR XML PATH('')), 1, 1, '' ) Concatenated
FROM TEST
``` | Try this:
```
DECLARE @Return VARCHAR(MAX)
SELECT @Return = COALESCE(@Return+' ','') + name
FROM dbo.TEST
SELECT @Return
``` | Return two rows as a single row | [
"",
"sql",
"sql-server",
""
] |
I want to create a table of **325** column:
```
CREATE TABLE NAMESCHEMA.NAMETABLE
(
ROW_ID TEXT NOT NULL , //this is the primary key
324 column of these types:
CHAR(1),
DATE,
DECIMAL(10,0),
DECIMAL(10,7),
TEXT,
LONG,
) ROW_FORMAT=COMPRESSED;
```
I replaced a... | I struggled with the same error code recently, due to a change in MySQL Server 5.6.20.
I was able to solve the problem by changing the innodb\_log\_file\_size in the my.ini text file.
In the release notes, it is explained that an innodb\_log\_file\_size that is too small will trigger a "Row size too large error."
<ht... | I tried all the solutions here, but only this parameter
```
innodb_strict_mode = 0
```
solved my day...
From the manual:
> The innodb\_strict\_mode setting affects the handling of syntax errors
> for CREATE TABLE, ALTER TABLE and CREATE INDEX statements.
> innodb\_strict\_mode also enables a record size... | MySQL: Error Code: 1118 Row size too large (> 8126). Changing some columns to TEXT or BLOB | [
"",
"mysql",
"sql",
"create-table",
""
] |
```
DELETE from Users
Where Id in (
SELECT TOP 200 u.id
FROM users u JOIN
playlists pl
ON u.id = pl.UserId LEFT OUTER JOIN
playlistitems pli
ON pli.PlaylistId = pl.id
GROUP BY u.id
HAVING count(pl.id) = 1 AND
count(pli.id) = 0
)
```
Are there any pitfalls... | I think it is pointless to join from `users` why don't you do this instead:
```
DELETE from Users
Where Id in (
SELECT TOP 200 pl.UserId
FROM playlists pl
LEFT OUTER JOIN
playlistitems pli
ON pli.PlaylistId = pl.id
GROUP BY pl.UserId
HAVING count(pl.id) = 1 AND
co... | Index each of the tables on the ID column. Preferably a clustered index, but not essential.
given that you already have indexes, try something like this:
```
;with cte as
(
select
u.id,
rank() over (partition by u.id) as rk
from users u
join playlists pl on pl.UserId = u.ID
join play... | Deleting rows via SQL query -- any way to speed up this query? | [
"",
"sql",
"sql-server",
""
] |
I'm trying to show a zero when no records where found for that particular id.

The image is the representation of what I'm trying to achieve. Right now I'm only getting the rows where he finds at least one record (so 3, 4 and 5).
Could someone please... | You want a row per status, so select from statusses. Then you want to count records from recipes and projectrecipes per status, so outer join them. Put your criteria in the ON clause, not in the WHERE clause, because when there is no matching record, fk\_projectrecipes\_projectid will be NULL. (You turn the outer join ... | I think you dont need to use the CASE, and also use RIGHT join so if no match comes in Join then also the result will come. Try below it should work.
```
SELECT recipes.fk_recipe_status, COUNT(projectrecipes.fk_projectrecipes_projectid)
FROM projectrecipes
RIGHT JOIN recipes
ON projectrecipes.fk_projectrecipes_recipe... | sql show 0 when no records where found | [
"",
"mysql",
"sql",
""
] |
I am new to MYSQL but have a basic understanding of SQL, and i am trying to say that if my parameter has not be set (ie null) then set it as JM.
What/where am i going wrong with the below script?
Thanks in advance
```
CREATE DEFINER=`james`@`%` PROCEDURE `Project_Status`(IN engineer VARCHAR (5))
BEGIN
SELECT
P... | I'm not sure I understand what you are trying to do.
If you want to use a value of `'JM'` instead of `NULL` when the input argument has a value of `NULL`, one way to get that kind of behavior is to declare a local variable in the procedure.
Check the value of the parameter, and set the value of the local variable acc... | Just try this:
```
SELECT
PP.pid_full,
PP.description_small,
PP.project_status,
PP.est_comp_date as 'Est Comp Date',
EP.engineer
FROM
project_pid pp
JOIN
eng_project_hours EP on PP.pid_full = EP.pid_full
where ep.engineer = coalesce(engineer,"JM");
``` | MYSQL if parameter null then set | [
"",
"mysql",
"sql",
"stored-procedures",
""
] |
I have table like
```
╔═══════════════════╗
║ Title ║
╠═══════════════════╣
║ Blogroll ║
║ Bottom Menu ║
║ Business ║
║ Entertainment ║
║ extend ║
╚═══════════════════╝
```
and my search criteria is like
```
WHERE title LIKE '%blogroller%'
```
obviously I will have... | You can do this but only with lots of manual effort:
```
select title,
(case when title like '%blogroller%' then 10
when title like '%blogrolle%' then 9
when title like '%blogroll%' then 8
. . .
else 0
end) as MatchLen
from table t
order by MatchLen de... | You don't have ability to do it at once, so you have to try all options one by one, but you can significantly optimize this process - that's what SQL for.
First, convert pattern into all possible patterns, then just find MAX from all possible LIKEs. Not sure if SQL will be able to really optimize it now, but maybe in ... | Ranking with LIKE keyword in SQL Server | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I use Rails 4. I have an application where i have a many-to-many relationship :
```
class User < ActiveRecord::Base
has_many :relationshipfollows, :foreign_key => "follower_id",
:dependent => :destroy
has_many :following, :through => :relationshipfollows, :source => :followed
end
class ... | My rescues solution was to add a integer numberfollowers in my Project model
But with another project and the rails guides (<http://guides.rubyonrails.org/active_record_querying.html>), I finally found the answer to my request
```
Project.joins(:relationshipfollows).select('projects.*, COUNT(followed_id) as user_coun... | Here's what I would do:
```
#app/models/project.rb
Class Project < ActiveRecord::Base
has_many :relationshipfollows, :foreign_key => "follower_id", :dependent => :destroy
has_many :followers, :through => :relationshipfollows, :source => :follower
scope :sort_by_followers, -> { joins(:followers).select(... | Order By Count on has_many :through | [
"",
"sql",
"ruby-on-rails",
"ruby",
"count",
"has-many-through",
""
] |
So I have a bit of a small issue:
```
GO
declare @datetime varchar(25);
select @datetime = getdate();
select cast(convert(varchar(8), @datetime, 112) as varchar)
GO
```
That is returning this: Apr 1 2
however this:
```
GO
declare @datetime varchar(25);
select @datetime = getdate();
select cast(convert(varchar(8), g... | You need to change the datatype of @datetime to DATETIME
```
declare @datetime DATETIME;
select @datetime = getdate();
select cast(convert(varchar(8), @datetime, 112) as varchar)
```
There is an implicit conversion from `varchar to datatime` which is happening at `select @datetime = getdate();` and which results in t... | Try the first one with this changes:
```
GO
declare @datetime DATETIME;
select @datetime = getdate();
select cast(convert(varchar(8), @datetime, 112) as varchar)
GO
```
The problem results from the varchar data type and the incorrect cast you use by selecting the result from `GETDATE()` into the varchar. | SQL Server getdate() returning weird results? | [
"",
"sql",
"sql-server",
""
] |
I am using SQL Server 2012,
How can I achieve following(Table 2) output from table 1 with sql script/tsql?
Table 1 :Current scenario
```
--------------------------------------------------
Year ReferredEachYear ActiveEachYear
--------------------------------------------------
2014 297 179 ... | If you are using SQL Server 2012, then you can use the cumulative sum function:
```
select cs.*,
sum(cs.ActiveEachYear) over (order by cs.[year]) as TotalActiveInSystem
from CurrentScenario cs
order by cs.[year] desc;
```
This function is not available in earlier versions of SQL Server. You would have to use s... | ```
SELECT T.Year,
T.ReferredEachYear
T.ActiveEachYear
(SELECT SUM(ActiveEachYear) FROM YourTable WHERE YourTable.Year <= t.Year) AS TotalActiveinSystem
FROM yourTable T
``` | How to calculate sum of the years into a new column for Current to previouse years | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2012",
""
] |
I'm very new to SQL and learing it from the book "SAMS Teach Yourself SQL in 24 hours". My concern is all about joins and grouping the select output. Here is the structure of my tables:
```
CREATE TABLE ORDERS_TBL
( ORD_NUM VARCHAR(10) NOT NULL primary key,
CUST_ID VARCHAR(10) NOT NULL,
PROD_ID VARCHAR(10) NOT NUL... | In TSQL you cannot select a column that is not included in a group by clause (never understood why in mysql you can because it does not make sense IMHO)
A dirty trick is to select with `min()` or `max()` or similar function (based on your needs) only one of the not aggregated column row.
```
SELECT max( P.PROD_DESC),... | The issue is that in most flavors of SQL, any columns you select without aggregating must appear in the `group by` clause.
If `PROD_DESC` is unique for each `PROD_ID`, then just group by `PROD_DESC` and you will be fine:
```
SELECT P.PROD_DESC, SUM(O.QTY)
FROM PRODUCTS_TBL AS P LEFT JOIN ORDERS_TBL AS O
ON P.... | MS SQL - Join with group by | [
"",
"sql",
"sql-server",
"group-by",
""
] |
So I am trying to filter out IDs from these 2 tables I 'union all'ed. Basically if the ID contains a certain name, I want to filter them out of the query. Here is an example
```
ID,Name
1,Mark
1,John
2,Peter
2,Matt
3,Henry
3,Matt
4,John
4,Olaf
```
So I do not want to include IDs that contain 'Matt' mea... | You would want to do something like this:
```
select * from table where id not in(
select Id from table where name like '%Matt%'
)
```
This excludes rows with name containing Matt
Exclude rows that equal Matt
```
select * from table where id not in(
select Id from table where name ='Matt'
)
``` | Use `not exists`:
```
select n.*
from names n
where not exists (select 1 from names n2 where n2.id = n.id and n2.name = 'Matt')
``` | Filtering out IDs that contain a certain value in another column | [
"",
"sql",
"sql-server-2008",
""
] |
In this SQL query:
```
SELECT * FROM CallRecords
WHERE DNIS = '3216547'
ORDER BY date DESC
```
But in the WHERE statement for DNIS ='' and I am looking to take the 3216547, but have it look at another table that I have a list of different DNIS's, for example:
```
3216547
9874560
7418523
```
So normally the statem... | ```
SELECT * FROM CallRecords
WHERE DNIS IN (SELECT DNIS FROM DNIS_TABLE)
ORDER BY date DESC
```
If you need all DNIS from the other table you could do that query. | ```
SELECT *
FROM CallRecords
WHERE DNIS IN (SELECT DNIS FROM OtherTable [...])
ORDER BY date DESC
``` | SQL Query with WHERE definitions are from another table | [
"",
"sql",
"sql-server",
""
] |
I am struggling to speed this SQL query up. I have tried removing all the fields besides the two SUM() functions and the Id field but it is still incredibly slow. It is currently taking 15 seconds to run. Does anyone have any suggestions to speed this up as it is currently causing a timeout on a page in my web app. I n... | I don't think this query is doing what you want anyway. As written, there are no relationships between the `Invoice` table and the `SalesOrder` table. This leads me to believe that it is producing a cartesian product between invoices and orders, so customers with lots of orders would be generating lots of unnecessary i... | You have a lot of LEFT JOIN
I don't see CustomerAccountStatus usage. Ou can exclude it
The `[InvoiceItem].[sNominalCode]` could be null in case of LEFT JOIN so add [InvoiceItem].`[sNominalCode] is not null or <THE IN CONDITION>`
Also add the `is not null` checks to other conditions | SQL query that uses a GROUP BY and IN is too slow | [
"",
"sql",
""
] |
I hope I can explain this well enough.
Say I have this table:
```
Owner
+--------+--------+
| Name | Type |
+--------+--------+
| Bob | Cat |
| Bob | Dog |
| Bob | Cow |
| Tim | Dog |
| Tim | Cat |
| Ted | Cat |
| Joe | Dog |
| Joe | Cat |
| Joe | Sheep |
+---... | ```
select name
from owner
where type in (select distinct type from owner where name = 'tim')
group by name
having count(distinct type) = (select count(distinct type) from owner where name = 'tim')
``` | If you are just trying to get all the persons who have more animals than Tim `has` then you can do it like
```
select Name from owners
group by Name
having count(distinct [Type]) > (select count(distinct type) from owners
where Name='tim')
``` | SQL resulting table satisfies two conditions | [
"",
"sql",
""
] |
Pretty new to SQL here - help would be much appreciated. I have a table with `Region`, `Month`, `Member ID`, and `Sales` (with multiple transactions per member). I just want to extract the top 2 members, based on sum of sales, per region, per month....so essentially:
```
Region Month MemberID Sales
-----------... | You can do this with `row_number()`:
```
select region, month, MemberId, sales
from (select region, month, MemberId, sum(sales) as sales
row_number() over (partition by region, month order by sum(sales) desc) as seqnum
from table t
group by region, month, MemberId
) t
where seqnum <= 2;
`... | If you are worried about ties (any you probably are as @Conrad Frix pointed out) you may prefer RANK() to ROW\_NUMBER().
I'll borrow sample data, use CTEs for clarity, apply my preferred formatting, and provide a [SQLFiddle](http://sqlfiddle.com/#!6/8a7dd/1).
```
CREATE TABLE MemberSales (
Region INT
,SalesMonth D... | SQL Server 2012: Select Top n based on multiple criteria | [
"",
"sql",
"sql-server-2012",
""
] |
I keep getting an incorrect syntax near the word ON, this code is from a suggested change from a previous post and I am trying to find where the error is and so far I am having no luck figuring out what punctuation mark I am missing. The code is
```
SELECT AC.REG_NR, AC.DIS_NR, AC.GEMSID, AC.TMS_ID, AC.EMP_NA, AC.EMP_... | There's something wrong with this query (ok, nothing new..). There is no alias on the final subquery, but it seems there's more.
The simplified and properly indented form might help you spotting the problem:
```
SELECT x
FROM dbo.AC_Source AS AC
INNER JOIN (
SELECT x
FROM (
SELECT x, ROW_NUMBER() OV... | For one thing, all subqueries need an alias. So, give the subqueries a name. I think it is something like this:
```
SELECT AC.REG_NR, AC.DIS_NR, AC.GEMSID, AC.TMS_ID, AC.EMP_NA, AC.EMP_SEX_TYP_CD,
AC.EMP_EOC_GRP_TYP_CD, AC.DIV_NR, AC.CTR_NR,
AC.JOB_CLS_CD_DSC_TE, AC.JOB_GRP_CD, AC.Job_Function, AC.Job_G... | Incorrect Syntax Error Near the word ON | [
"",
"sql",
"sql-server",
""
] |
I would like to find all records in the column of one table that are not in a column of another. I can do so with this query:
```
SELECT
kywd
FROM
from_client
WHERE
kywd NOT IN
(SELECT
kywd
FROM
from_me);
```
However, I would like to extend this to allow for some pa... | `not exists` is likely to be faster than join
```
select kywd
from from_client
where not exists (
select 1
from from_me
where position(from_client.kywd, kywd) > 0
)
``` | ```
SELECT from_client.kywd
FROM from_client
LEFT JOIN from_me
ON from_client.kywd LIKE '%' || from_me.kywd || '%'
WHERE from_me.kywd IS NULL
``` | select record in one table that are not in another with a pattern match | [
"",
"sql",
"regex",
"postgresql",
""
] |
Is there a good way to express within SQL to select a specific row if a column is matched, otherwise to select a more general row? Something like:
```
SELECT name FROM names
WHERE (colA = @colA OR colA = 'ALL')
```
I just want it to return the one specific record if it exists, otherwise return the generi... | @Blorgbeard answer (using top 1 and order by) is probably the best way but just to be different you could also use a sub-query and not exists:
```
SELECT name FROM names
WHERE (colA = @colA) OR (colA = 'ALL' AND NOT EXISTS(
SELECT name FROM names
... | This query, although not pretty, should do what you want:
```
SELECT TOP 1 name FROM names
WHERE (colA = @colA OR colA = 'ALL')
ORDER BY CASE WHEN colA='ALL' THEN 1 ELSE 0 END
```
Edit: For multiple columns, I think what you would want is this:
```
SELECT TOP 1 name FROM names
WHERE (colA = @colA AND colB = @colB... | COALESCE in Where clause? | [
"",
"sql",
"sql-server-2008",
"stored-procedures",
""
] |
Trying to use sum to show decimals, but its converting it to integer. Very unsure what is wrong. Here is the sql fiddle:
<http://sqlfiddle.com/#!2/b2961/1>
SQL query:
```
Select sum(PH) as PH from googlechart;
``` | As per the comment of the user, they didn't intend to Sum the values of the field, but rather just wanted to use the values numerically. The answer previous was
```
select SUM(CAST(REPLACE(PH, ",", ".") AS DECIMAL(5,2))) from googlechart;
```
The actual answer should have been:
```
select CAST(REPLACE(PH, ",", ".") ... | Change PH value as `08.11` and `09.34` instead of `08,11` and `09,34`
```
INSERT INTO `googlechart` (`id`, `Date`, `Time`, `PH`, `Chlorine`, `Temperature`) VALUES
(7, '2014-04-01', '09:00:00', '08,11', '9.00', '12.00'),
(9, '2014-04-02', '11:00:00', '09,34', '10.34', '2.34');
```
to
```
INSERT INTO `googlechart` (`i... | Sum function not returning decimals | [
"",
"mysql",
"sql",
"sum",
"decimal",
""
] |
I am having an issue. I have declared a cursor and when i fetch it i want to print a variable (type nvarchar) but for each row i get only the first letter
Here is my code :
```
DECLARE @loginSoftware nvarchar
DECLARE @loginId int
DECLARE @softwareId int
DECLARE @passwordSoftware nvarchar
DECLARE @SoftwareFamily nvarch... | DECLARE @loginSoftware NVARCHAR
SET @loginSoftware = 'fdjafs'
PRINT @loginSoftware
## Will give you only the first letter.
DECLARE @loginSoftware NVARCHAR (2000)
SET @loginSoftware = 'fdjafs'
PRINT @loginSoftware
Will give you all of it....So basically you also have to specify the data length too. | Make you `nvarchar` variables have a length. If you don't declare is like `nvarchar(20)` then the default length is 1. | Transact SQL Print only first letter using cursor | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I want to update multiple columns of a table in DB2 with single Update statement.
Any hint or idea will be appreciable. Thanks. | The update statement in all versions of SQL looks like:
```
update table
set col1 = expr1,
col2 = expr2,
. . .
coln = exprn
where some condition
```
So, the answer is that you separate the assignments using commas and don't repeat the `set` statement. | If the values came from another table,
you might want to use
```
UPDATE table1 t1
SET (col1, col2) = (
SELECT col3, col4
FROM table2 t2
WHERE t1.col8=t2.col9
)
```
Example:
```
UPDATE table1
SET (col1, col2, col3) =(
(SELECT MIN (ship_charge), MAX (ship_charge) FROM orders),
'07/01/20... | How to update multiple columns in single update statement in DB2 | [
"",
"sql",
"database",
"db2",
"sql-update",
""
] |
I want to create a view between a table that has data and another table that has a flag that the field must show or not.
**TABLE\_EXAMPLE**
```
+---------+---------+---------+-----------------+
| id | field_1 | field_2 | field_3 |
+---------+---------+---------+-----------------+
| 1 | test | 50... | If the `REFERENCE_TABLE` has flags for all fields of each entity, then you can use this:
```
SELECT
T1.ID,
MAX(CASE WHEN T2.field_name = 'field_1' AND T2.show = 1 THEN T1.field_1 END) field_1,
MAX(CASE WHEN T2.field_name = 'field_2' AND T2.show = 1 THEN T1.field_2 END) field_2,
MAX(CASE WHEN T2.field_name = 'f... | Here is one method where you join to the table three times and then use a case statement to determine what the value is for each column:
```
select e.id,
(case when r1.show then e.field_1 end) as field_1,
(case when r2.show then e.field_2 end) as field_2
(case when r3.show then e.field_3 end) as f... | How to create a Mysql View between 2 tables | [
"",
"mysql",
"sql",
"view",
"relation",
""
] |
suppose there are records as follows:
```
Employee_id, work_start_date, work_end_date
1, 01-jan-2014, 07-jan-2014
1, 03-jan-2014, 12-jan-2014
1, 23-jan-2014, 25-jan-2014
2, 15-jan-2014, 25-jan-2014
2, 07-jan-2014, 15-jan-2014
2, 09-jan-2014, 12-jan-2014
```
The requirement is to write an SQL select statment which wo... | This is a slightly modified query from similar question:
[compute sum of values associated with overlapping date ranges](https://stackoverflow.com/questions/22232796/compute-sum-of-values-associated-with-overlapping-date-ranges/22236718#22236718)
```
SELECT "Employee_id",
SUM( "work_end_date" - "work_start_d... | This is a tricky problem. For instance, you can't use `lag()`, because the overlapping period may not be the "previous" one. Or different periods can start and or stop on the same day.
The idea is to reconstruct the periods. How to do this? Find the records where the periods start -- that is, there is no overlap with ... | Sum of working days with date ranges from multiple records (overlapping) | [
"",
"sql",
"oracle",
"sum",
"overlap",
""
] |
I have this statements
```
SELECT @startdate = DATEADD(wk, DATEDIFF(wk,0,GETDATE()), -7) -- Monday of previous week
SELECT @enddate = DATEADD(wk, DATEDIFF(wk,0,GETDATE()), -1) -- Sunday of previous week
```
and I want to convert @startdate and @enddate to numbers in the following format 'yyyymmdd' | ```
SELECT CONVERT(nvarchar(8), @StartDate, 112)
```
Will convert `2014-03-31` to `20140331` | The easiest way is to use `year()`, `month()`, and `day()`:
```
select @startdate = year(getdate())*10000 + month(getdate()) * 100 + day(getdate())
``` | how can I convert a date var to a number is sql? | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
Dear all and thank you in advance.
**Problem:**
Instead of having two dropdown boxes for list A and list B. I would like to combine the two lists (they do relate) and display them to the user as 1 list. Then split it back into two so that I can store the relevant info.
List 1
```
Machines
1. Machine x
2. Machine y
... | Assuming a and b are numeric variables as your 3 functions suggest I would use the .ItemData() property of the items in the combined list just like Mark and use division and remained to obtain the separate parts:
```
Public Function joinAB(a As Long, b As Long) As Long
joinAB = a * 100 + b
End Function
Public Funct... | There are probably a few solutions to this.
The simplest is that you create a unique 32-bit integer field on your join table. This can then be embedded in the ItemData property of the VB6 ListBox.
A couple of helper functions for this are:
```
Private Sub AddListBoxItem(ByRef lst as ListBox, ByVal in_nKey As Long, B... | Two lists combined into 1 dropdown box | [
"",
"sql",
"list",
"vb6",
""
] |
In a select query I calculate a field using a nested select. I would like to order the results by the calculated field (rank), however Access does not recognize the field rank. (When I run the query, Access asks for the parameter value of rank.)
```
SELECT
*,
(select count(*)
from tbl as tbl2
where tbl.custo... | Use a Derived table
```
SELECT * FROM
(
SELECT
*,
(select count(*)
from tbl as tbl2
where tbl.customers > tbl2.customers and tbl.dept = tbl2.dept
) + 1 as rank
FROM tbl
) as newtbl
ORDER BY rank
``` | Think you'd have to:
```
order by ((select count(*) from tbl as tbl2 where
tbl.customers > tbl2.customers and tbl.dept = tbl2.dept) + 1)
``` | MS Access: Order by calculated field (using alias) | [
"",
"sql",
"ms-access",
""
] |
I have populated a DropDownList with values from an SQL statement and it works.
```
Try
cmdStr = "SELECT [idt],[col1] FROM [test];"
Using conn As New SqlConnection(connStr)
Using cmd As New SqlCommand(cmdStr, conn)
conn.Open()
cmd.ExecuteNonQuery()
... | update it to use DropDownList1.SelectedItem.Text
```
Try
cmdStr = "SELECT [datetime],[col1],[col2],[col3] FROM [test] WHERE [idt]=@idt;"
Using conn As New SqlConnection(connStr)
Using cmd As New SqlCommand(cmdStr, conn)
conn.Open()
cmd.Parameters.AddWithValue... | ```
DropDownList1.DataSource = ds.Tables(0)
DropDownList1.DataTextField = "idt"
DropDownList1.DataValueField = "idt"
DropDownList1.DataBind();
```
You don't need to select "col1" column . Because You don't use it.
Then
Use SelectedValue property
```
cmd.Parameters.AddWithValue("@idt", DropDownList1.SelectedVal... | DropDownList showing the SQL value | [
"",
"asp.net",
"sql",
""
] |
I am trying to do a decode against an Oracle server and return a fiscal year if date ranges fall in between what is listed below. I keep getting 'ORA-00907: missing right parenthesis' and I am sure it is something simple or maybe I am not using correct syntax for the date range but any help would be appreciated. Thanks... | I figured out a query that works. Not sure if this is best practices or not but here my is code:
```
SELECT DECODE(FISCAL_QUARTER,'FY12 Q1',2012,'FY12 Q2',2012,'FY12 Q3',2012,
'FY12 Q4',2012,'FY13 Q1',2013,'FY13 Q2',2013,'FY13 Q3',2013,'FY13 Q4',2013,'FY14
Q1',2014,'FY14 Q2',2014,'FY14 Q3',2014,'FY14 Q4',2014,2015)as ... | You cannot use `DECODE` to test anything other than equality. You can, however, use the much more robust and much more standard `CASE` function
```
CASE WHEN issue_dt >= date '2011-07-01' AND issue_dt <= date '2012-06-30'
THEN '2012'
WHEN issue_dt >= date '2012-07-01' AND issue_dt <= date '2013-06-30'
T... | How do I decode a row of data using a date range as my parameter | [
"",
"sql",
"oracle",
"syntax-error",
"peoplesoft",
""
] |
I recently upgraded from MySQL Workbench 5.2.47 up to 6.1.
After making changes to a table via the Gui grid interface on the old version, I'd hit the 'Apply' button and have a popup confirming to make the change. This popup had the SQL code that would run in order to make the change that I made via the UI interface. I... | It is indeed a bug :-(
In the MySQL bug database:
<http://bugs.mysql.com/bug.php?id=72169>
<http://bugs.mysql.com/bug.php?id=72155> | Functionality restored in CE release: 6.1.7
<http://dev.mysql.com/downloads/file.php?id=452662> | MySQL Workbench: How can I see the detailed SQL query and errors when I use the "Apply" button? (confirmation popup) | [
"",
"mysql",
"sql",
"mysql-workbench",
""
] |
Select value from CODE row if results of both criterias are equal.
Example of a condition:
> DAYS = 30, RATE 2
> AND
> DAYS = 60, RATE 0
Table
```
ID | CODE| DAYS| RATE|
1 | 01 | 30 | 2 |
2 | 05 | 20 | 3 |
3 | 01 | 60 | 0 |
4 | 06 | 30 | 3 |
...
```
First part is
```
SELECT * FROM Tablen... | You need a self-join:
```
SELECT DISTINCT t1.code
FROM Tablename t1
INNER JOIN Tablename t2
ON t1.code = t2.code
WHERE t1.days = 30 AND t1.rate = 2
AND t2.days = 60 AND t2.rate = 0
``` | ```
SELECT DISTINCT CODE FROM Tablename
WHERE (DAYS = 30 AND RATE = 2)
OR (DAYS = 60 AND RATE = 0)
``` | select one value if result of both criterias is equal | [
"",
"sql",
"select",
""
] |
I am developing a program that uses a MySQL database to store data. I have a table (simplified here):
```
+---------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+------------------+------+-----+---------+----------------+
... | First way: use [`LEAST()`](https://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_least) and [`GREATEST()`](https://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_greatest):
```
UPDATE t SET someNum=GREATEST(-3,LEAST(3,someNum+2)) WHERE dataId=78225;
```
This is the most easy w... | use [GREATEST](https://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_greatest) and [LEAST](https://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_least) instead of MAX and MIN
You could also use a CASE WHEN
```
update table
set someNum = CASE WHEN SomeNum +2 > 3 THEN 3
... | Limiting a field's value in MySQL? | [
"",
"mysql",
"sql",
"max",
"min",
""
] |
Question - let's say I have 2 tables.
Table 1 - name is permission\_list, columns are ID (unique ID), col\_ID, user\_ID
Table 2 - name is list\_entries, Columns are ID (unique ID), title, description, status
I want to select all the rows from table 2 that have status of 'public' as well as all the rows from table 2 ... | Here you go:
```
SELECT DISTINCT table2.* from table2
LEFT JOIN table1 USING (id)
WHERE status='public'
OR user_ID='someuser';
``` | You need to get some education on JOIN for your first thing, and the second thing is called DISTINCT.
Start here... <https://www.google.com/>
You have not specified your join condition so we can't give you code samples really. Also the way you worded your question, I'm not entirely sure you don't want a UNION. Read u... | MYSQL - QUERY FROM TWO TABLES | [
"",
"mysql",
"sql",
"select",
"join",
""
] |
I'm creating a table in Oracle 11g like this:
```
CREATE TABLE EXAMPLE (
ID VARCHAR2(10) PRIMARY KEY,
NAME VARCHAR2(100),
SHORT VARCHAR2(50),
CURRENCY CHAR(3)
);
```
Is it possible to create a **foreign key constraint** or even a **check constraint** on `CURRENCY` to a built-in Oracle table that cont... | Note: Edited to include @A.B.Cade's suggestion.
Unfortunately you can't directly add a constraint, as the currencies data is available through a system a view. You can, however, create your own table with that information and then create the foreign key. Here's an example of how you can do it.
```
CREATE TABLE curren... | You can get a list of ISO currencies from a built in view in oracle:
```
select utl_i18n.GET_DEFAULT_ISO_CURRENCY(value) iso_cur
from v$nls_valid_values
where parameter = 'TERRITORY'
```
But as Nuno Guerreiro said, you'll need to create a table from these results and add a foreign key to the new table. | Does oracle provide a built-in currency table for me to use as constraints? | [
"",
"sql",
"oracle",
"oracle11g",
"constraints",
""
] |
I'm sum when the group state= 0,1,2 and sum 0 when it show 0
My tables:
```
|policies|
|id| |client| |policy_business_unit_id| |cia_ensure_id| |state|
1 MATT 1 1 0
2 STEVE 2 1 0
3 BILL ... | If you need to group all values for state = 0 or 1 or 2 together, then your query must be a little different. Try this.
```
SELECT
SUM(CASE WHEN p.state = 0 THEN 1 ELSE 0 END) AS state_0,
SUM(CASE WHEN p.state = 1 THEN 1 ELSE 0 END) AS state_1,
SUM(CASE WHEN p.state = 2 THEN 1 ELSE 0 END) AS state_2,
... | replace this
```
SELECT
IF( p.state =0, COUNT( p.state ) , 0 ) AS state_0,
IF( p.state =1, COUNT( p.state ) , 0 ) AS state_1,
IF( p.state =2, COUNT( p.state ) , 0 ) AS state_2,
```
by
```
SELECT
sum(CASE WHEN p.state =0 THEN 1 ELSE 0 end) AS state_0,
sum(CASE WHEN p.state =1 THEN 1 ELSE 0 E... | How can sum group values? | [
"",
"mysql",
"sql",
""
] |
In My project, we connecting to MS Access from MS Excel, in excel we have one dropdown (medd) with Yes or No values. At the same time, in MS Access, we have column Med\_D with Y or N values.
So, if the user selects 'Yes' from the dropdown, then it should fetch the MS Access rows where Med\_D = Y.
If the user selects '... | Sub MakeDynamicSQL()
Const SQL As String = "select \* from YourAccessTable"
Dim sWhereClause As String
```
Select Case Cells(1, 1).Text ' cell A1 contains Y or N
Case "Y": sWhereClause = " where Med_D = 'Y'"
Case "N": sWhereClause = " where Med_D in ('Y','N')"
Case Else: MsgBox "error": Exit Sub
End ... | use this:
```
Select * from "Table Name" Where Med_D = "xxxxx"
```
xxxxx is the dropdown with Y and N
Im guessing your using ADODB connection? | How to assign the value to the Access column in the where clause? | [
"",
"sql",
"vba",
"excel",
""
] |
So I have an app I'm working on with two models. Users can create objects with certain traits
I don't want a user to be able to find their own objects.
How do I limit the query?
```
def self.search(search)
where(['primarybreed LIKE ?', "%#{search}%"]).where(:user_id != current_user.id)
end
```
current user breaks t... | For Rails 4.x, use this:
```
def self.search(search, current_user_id)
where(['primarybreed LIKE ?', "%#{search}%").where.not(user_id: current_user_id])
end
```
and you can call it as:
```
@dog = Dog.search(params[:search],current_user.id).sample if params[:search].present?
``` | May be this will solve your problem
```
def self.search(search, current_user_id)
where(['primarybreed LIKE and user_id != ?', "%#{search}%",current_user_id])
end
``` | Exclude User's Built Objects From Search | [
"",
"html",
"sql",
"ruby-on-rails",
"ruby",
""
] |
So I have a table with users
A few users are "owners"
A user can have a owner
Now I want to select the owner from the user (Both in the same table)
Example:
Owner:
```
user_id: 34
user_name: hiimowner
user_owner_id: NULL
```
User:
```
user_id: 63
user_name: randomperson
user_owner_id: 34
```
Now I'm looking for ... | ```
SELECT * FROM table AS t1
JOIN table AS t2
ON t1.user_id = t2.user_owner_id
WHERE t2.user_id = 63
``` | try this,
```
Select u.*,o.user_name from User as u
left join User o on o.user_id = u.user_owner_id
```
If want to filter specific record then add where clause,
```
Select u.*,o.user_name from User as u
left join User o on o.user_id = u.user_owner_id
where u.user_id = 63
``` | Select another user from same table | [
"",
"sql",
""
] |
I got a mysql database with approx. 1 TB of data. Table fuelinjection\_stroke has apprx. 1.000.000.000 rows. DBID is the primary key that is automatically incremented by one with each insert.
I am trying to delete the first 1.000.000 rows using a very simple statement:
```
Delete from fuelinjection_stroke where DBID ... | I believe that you table becomes locked. I've faced same problem and find out that can delete 10k records pretty fast. So you might want to write simple script/program which will delete records by chunks.
```
DELETE FROM fuelinjection_stroke WHERE DBID < 1000000 LIMIT 10000;
```
And keep executing it until it dele... | **Are you space deprived? Is down time impossible?**
If not, you could fit in a new INT column length 1 and default it to 1 for "active" (or whatever your terminology is) and 0 for "inactive". Actually, you could use 0 through 9 as 10 different states if necessary.
Adding this new column will take a looooooooong time... | mysql - Deleting Rows from InnoDB is very slow | [
"",
"mysql",
"sql",
"innodb",
""
] |
I have posted something similar before, but I am approaching this from a different direction now so I opened a new question. I hope this is OK.
I have been working with a CTE that creates a sum of charges based on a Parent Charge. The SQL and details can be seen here:
[CTE Index recommendations on multiple keyed tabl... | The best SQL Server can do for you here is to push the filter on `ChargeID` down into the anchor part of the recursive CTE inside the view. That allows a seek to find the only row you need to build the hierarchy from. When you provide the parameter as a constant value SQL Server can make that optimization (using a rule... | Next to get to a solution, I would recommend to SELECT INTO the CTE into e temp table and join from there. From personal experience joining with CTE my query was returning for 5mins while simply inserting the data generated by CTE into a temp table brought it down to just 4secs. I was actually joining two CTEs together... | CTE very slow when Joined | [
"",
"sql",
"sql-server-2008-r2",
"common-table-expression",
""
] |
I have the following table structure
```
id dateChanged changeType changeID
```
which has the following data
```
1 2014-04-01 memEdit 205
2 2014-04-01 memEdit 205
3 2014-03-31 memEdit 1
4 2014-04-01 memEdit 1
5 2014-04-01 memEdit 3
```
Now i want to get the latest record for each c... | ### 1. OLD not working query
```
SELECT * FROM `your_table`
GROUP BY `changeID`
ORDER BY `id` DESC
```
### 2. Working query
The problem is with MySQL's non-standards craziness.
MySQL does not force you to `GROUP BY` every column that you include in the `SELECT` list. As a result, if you only `GROUP BY` one column b... | This can be done with a simple subquery:
```
select * from table t
where t.dateChanged =
(select max(dateChanged)
from table t2
where t2.id = t.id)
;
```
Let me know if this helps! | get latest record in group | [
"",
"mysql",
"sql",
""
] |
I have two tables, users and contestants. I'm trying to select the max contestant ID that has a profile picture(which is on the user table)
Heres my terrible SQL:
```
SELECT u.thumbnail, u.id FROM users AS u
INNER JOIN
(
SELECT c.id, c.user_id FROM contestants AS c
WHERE u.id = c.users_id
AND c.id = (select max(c.i... | Whenever you are performing a join operation, you are actually joining two table. The subquery you wrote here, for instance, is working as a separate table. Hence, you have to use an alias to this table. That's the reason behind your error message.
Your query:
```
SELECT u.thumbnail, u.id FROM users AS u
INNE... | try this:
```
SELECT u.thumbnail, u.id
FROM users AS u
INNER JOIN
(
SELECT c.id, c.user_id FROM contestants AS c
WHERE u.id = c.users_id
AND c.id = (select max(c.id))
)A
WHERE u.thumbnail IS NOT NULL
``` | SQL Join with MAX(). | [
"",
"mysql",
"sql",
"inner-join",
""
] |
I have a select statement which displays a list of companies.
```
SELECT distinct [Company]
FROM [Records]
```
How can I add the entry "ALL" as the first item on the returned list? | Use `union all` and `order by`:
```
select company
from ((select distinct company, 1 as ordering from records)
union all
(select 'ALL', 0)
) t
order by ordering;
```
In practice, the following would seem to work:
```
select 'ALL' as company
union all
select distinct company from records;
```
Howeve... | You can use `UNION ALL` and add order:
```
SELECT [Company] FROM
(SELECT 'All' as [Company], 0 as RecordOrder
UNION ALL
SELECT distinct [Company], 1 as RecordOrder
FROM [Records]) X
ORDER BY RecordOrder
``` | SQL add ALL to select statement | [
"",
"sql",
"sql-server-2008",
""
] |
Here's my MySQL query and what it returns:
```
SELECT email, COUNT(*) AS num
FROM collectors_users
WHERE subscribed != 'NO'
AND lastLogin IS NULL
GROUP BY email
ORDER BY dateadded DESC;
```

I only want to return results where num > 1. I tried... | After the GROUP BY clause, and before the ORDER BY clause add this:
```
HAVING COUNT(*) > 1
```
The `HAVING` clause gets applied nearly last in the execution plan, after all of the rows have been prepared, prior to the `LIMIT` clause. This is most useful for conditions that can't be checked while rows are being acces... | Use `HAVING` clause. Or another way:
```
SELECT * FROM
(SELECT email, COUNT(*) AS num
FROM collectors_users
WHERE subscribed != 'NO'
AND lastLogin IS NULL
GROUP BY email
ORDER BY dateadded DESC;
) T
WHERE num>1
``` | How do I show all results where the GROUP BY count is greater than 1 in MySQL? | [
"",
"mysql",
"sql",
"count",
"group-by",
""
] |
I have a table look like this :
```
acronym | word
FCN | FCN
FCN | Fourth Corner Neurosurgical Associates
FHS | FHS
HW | HW
```
As you see, some acronyms have matching words and some don't. I want to keep the acronyms that have matching words. For the acronyms that don't have matching word, I'd like ... | Assuming there can't be any 'bad' words:
```
DELETE myTable
FROM myTable del
WHERE [acronym] = [word]
AND EXISTS ( SELECT *
FROM myTable lw -- Longer Word
WHERE lw.[acronym] = del.[acronym]
AND Len(lw.[word]) > Len(lw.[acronym]) )
```
Or do you want to avo... | Depending on your data, you may be able to use a combination of Distinct and a Case statement
```
select distinct acronym,
(case acronym when word then word else acronym end) as Abbr
from acronyms
``` | sql server remove duplicate acronym | [
"",
"sql",
"sql-server",
""
] |
1. Is it possible to do something like the following with SQL, not PL/pgSQL (note if it's only possible with PL/pgSQL, then how)?
```
IF password = 'swordfish' THEN
SELECT a, b, c FROM users;
ELSE
SELECT -1; -- unauthorized error code
END IF;
```
2. Ideally, could I wrap the above in a fun... | Algorithm
1. Select `1` into `a` (authorized) if we find a `user_id_1`-`session_id` match.
2. Select `0, NULL, NULL` into `u` (unauthorized) if we didn't find a match in step 1.
3. Select `user_id, body, sent` into `s` (select) if we did find a match in step 1.
4. Union `u` and `s`.
Code
```
-- List messages between... | The PL/pgsql function below returns the `messages` sent between `user_id` & `with_user_id` if the `user_id`:`key` pair is authorized, as determined by the user-defined function (UDF) `user_auth`. Otherwise, it returns one row with `from = -1` . The other UDF, `pair`, is a [unique unordered pairing function](http://www.... | PostgreSQL: CASE: SELECT FROM two different tables | [
"",
"sql",
"postgresql",
"select",
"case",
"create-function",
""
] |
I have a SQL problem. I have a table where a user gets a row for every experience they complete. The schema looks similar to this fiddle: <http://sqlfiddle.com/#!2/5d6a87/4>
I am trying to write a query that lists every user that has expid 1-5. So in my example it would list userids: 1,2, and 4. Since userid 3 does no... | What you would like to use is "group by"
the query would look like it:
```
select userid
from some_table
group by userid
having count(*)>=5
```
you can also be creative and force 5 different expeids by
```
select userid
from some_table
group by userid
having count(distinct expid)>=5
```
light reading about group by... | Here
```
SELECT * FROM some_table GROUP BY UserID having count(*)>= 5;
```
They way I see it should be like this but your question is not 100% clear, since you said 5 rows for every ExpID.
```
SELECT * FROM some_table GROUP BY UserID, ExpID having count(*)>= 5;
``` | mysql query that a user has a row for every experience id | [
"",
"mysql",
"sql",
"validation",
""
] |
I created a dynamic stored procedure that starts as follows.
I can save this without errors but when I execute it it seems it doesn't recognise the @temp variable as it throws the following error: "Must declare the table variable "@temp"."
Could this be because of wrong quotes / escaping and if, how do I have to chan... | As I have already mentioned in comments section, Dynamic Sql has its own scope, any variable declared outside of that scope arent visible to dynamic sql, Your have to declare the variable inside your dynamic sql. Something like as follows....
```
SET @sql = N' DECLARE @temp AS TABLE
(
rankin... | Hope you are doing fine,
well i think you may reconsider using a variable table because SQL won't understand what the @temp variable means when you will execute the EXEC(@sql), i recommand using a temp table instead of a variable table, here's the new code :
```
BEGIN
SET NOCOUNT ON;
BEGIN
if object_id('tem... | SQL Server: issue with declaring variable in dynamic SQL | [
"",
"sql",
"sql-server",
"select",
"dynamic",
"dynamic-sql",
""
] |
I am trying to calculate Month over Month % change on data rows. For example my current output is:
```
DataDate |LocationId|Payment|MoM [Current placeholder column in script]
12-1-2013|LocationA |$5.00 |
1-1-2014 |LocationA |$10.00 |
2-1-2014 |LocationA |$100.00|
12-1-2013|LocationB |$50.00 ... | This works on SQL Server 2012:
```
with x as (
select datadate, locationid, payment,
lag(payment) over(partition by locationid order by datadate) as prev_payment
from table
)
select *, (payment/prev_payment)-1
from x
``` | Although dean's solution is better, I just wanted to also post a solution for people that don't have SQL Server 2012 for completeness' sake (and since I had already started on it before dean posted his).
This can be accomplished using Common Table Expressions and the `Row_Number()` function:
```
WITH CTE AS
(
SELECT... | Trying to Calculate Month over Month percentage increase/decrease | [
"",
"sql",
"sql-server",
"excel",
"sum",
"calculated-field",
""
] |
```
SELECT .... ColumnNames ...
INTO [FOUND_DUPLICATES]
FROM [FIND_DUPLICATES] AS FD
WHERE FD.[Contract No] IN
(SELECT [Contract No],
[Vehicle Identity number (VIN)],
COUNT(*) AS Anzahl
FROM FIND_DUPLICATES
GROUP BY
[Contract No],
[Vehicle Identity number ... | Adding another sub query should work?
```
Select .... ColumnNames ...
INTO [FOUND_DUPLICATES]
FROM [FIND_DUPLICATES]
AS FD
where FD.[Contract No]
IN ( Select [Contract No] from (Select
[Contract No],
[Vehicle Identity number (VIN)],
COUNT(*) AS Anzahl
from FIND_DUP... | You can use this:
```
SELECT .... ColumnNames ...
INTO [FOUND_DUPLICATES]
FROM [FIND_DUPLICATES] AS FD
WHERE FD.[Contract No] IN
(
SELECT
[Contract No]
FROM FIND_DUPLICATES
GROUP BY
[Contract No],
[Vehicle Identity number (VIN)]
HAVING COUNT(*) >1
)
```
or use correlated subquery:
```
SELE... | Select into Table from Table2 where column in (Subquery) | [
"",
"sql",
"sql-server",
"select",
"select-into",
""
] |
I want to fetch all columns of a table except of columns of type serial. The closest query to this problem I was able to come up with this one:
```
SELECT column_name FROM information_schema.columns
WHERE table_name = 'table1' AND column_default NOT LIKE 'nextval%'
```
But the problem is its also excluding/filtering ... | ### About `null`
`'anything' NOT LIKE null` yields `null`, not `true`.
And only `true` qualifies for filter expressions in a `WHERE` clause.
Most functions return `null` on `null` input (there are exceptions). That's the nature of `null` in *any* proper RDBMS.
If you desire a *single* expression, you *could* use:
... | The easiest method is:
```
where length(column_name) > 0
``` | Behaviour of NOT LIKE with NULL values | [
"",
"sql",
"postgresql",
"null",
"information-schema",
""
] |
I have a Table which is having a column with junk values
```
DECLARE @tmp TABLE(junkValues nvarchar(max))
INSERT into @tmp (junkValues)
VALUES ('@{''id''= ''63FCE3C0-B6FE-4FFE-8BC8-506A338455DD''; Value="ABC"; Other="ddd"}')
INSERT into @tmp (junkValues)
VALUES ('@{''id''= ''C10560BA-7059-4AC5-B9ED-77BAC7182BD7''; O... | A bit complex, but it Works!, please try following,
```
DECLARE @tmp TABLE(junkValues nvarchar(max))
INSERT into @tmp (junkValues)
VALUES ('@{''id''= ''63FCE3C0-B6FE-4FFE-8BC8-506A338455DD''; Value="ABC", Other="ddd"}')
INSERT into @tmp (junkValues)
VALUES ('@{''id''= ''C10560BA-7059-4AC5-B9ED-77BAC7182BD7''; Other=... | May this help you..
```
DECLARE @tmp TABLE(junkValues nvarchar(max))
INSERT into @tmp (junkValues)
VALUES ('@{''id''= ''63FCE3C0-B6FE-4FFE-8BC8-506A338455DD''; Value="ABC", Other="ddd"}')
INSERT into @tmp (junkValues)
VALUES ('@{''id''= ''C10560BA-7059-4AC5-B9ED-77BAC7182BD7''; Value="XYZ", Other="ddd"}')
SELECT
S... | Split string and save it to temporary table | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
How to convert this result:
```
Group | Sum
Services | 11120.99
Vendas | 3738.00
```
Into:
```
Group | Sum
Services | 74.84
Vendas | 25.16
```
That is, the second displays the results as percentages of total.
This is what I tried:
```
SELECT categories.cat AS 'Group', SUM(atual) AS 'Sum'
FROM `t... | you can left join a total sum that is not grouped or split up, and divide that by your sum query. this way you are just doing the total select once for faster runtime
```
SELECT cat, sum_atual, sum_atual/total_atual as percent_atual
FROM
( SELECT categories.cat AS cat, SUM(atual) AS sum_atual
FROM `table1`
... | ```
SELECT categories.cat AS categoria,
SUM(atual) * 100 / (select sum(atual) from table1) AS percentages
FROM `table1`
INNER JOIN categories ON table1.category_id=categories.id
GROUP BY categoria
``` | MySQL query to calculate percentage of total column | [
"",
"mysql",
"sql",
""
] |
I have a little problem, I do have a table like this :
```
CREATE TABLE IF NOT EXISTS `t_ot_prestation` (
`id_ot` int(11) NOT NULL,
`id_prestation` int(11) NOT NULL,
PRIMARY KEY (`id_ot`,`id_prestation`)
) ENGINE=MyISAM;
```
What I would like to get is to get distinct id\_ot according to multiple id\_prestatio... | That won't work, because no row could match that condition. Instead, use `group by` and `having`:
```
SELECT id_ot
FROM `t_ot_prestation`
GROUP BY id_ot
HAVING sum(case when `id_prestation` = 723 then 1 else 0 end) > 0 and
sum(case when `id_prestation` = 1177 then 1 else 0 end) > 0;
```
Each condition in the ... | The WHERE clause is looked at per record. There is no single record that has both id\_prestation =723 and id\_prestation = 1177, of course.
Here is one way to solve this (provided your dbms supports INTERSECT):
```
SELECT id_ot
FROM `t_ot_prestation`
WHERE `id_prestation` =723
INTERSECT
SELECT id_ot
FROM `t_ot_presta... | How to get row when matching multiple AND? | [
"",
"sql",
""
] |
I have a basic table which outputs.
```
field1
a
b
c
```
Then i want to add single quotes and a comma so currently i have a simple QUOTENAME.
```
QUOTENAME(field1,'''')
```
Which outputs the following results.
```
field1
'a'
'b'
'c'
```
But i cant figure out how to get the QUOTENAME to output results ... | Try:
```
QUOTENAME(field1,'''')+','
``` | I know you got your answer but just wanted to make an addition if someone else looks at this and is wondering how to get rid of the last comma after the last value in case they are using the resultset for a dynamic query.
```
Declare @MyString nvarchar(max)
select @MyString += QuoteName (field1.'''') + ','
from YourTa... | SQL QUOTENAME adding single quotes and a comma | [
"",
"sql",
"function",
"quotename",
""
] |
How do i combine a SUM and MAX in a single query?
Lets say i have a orderrule:
ProductID \ Quantity
I Could say:
```
Select ProductID,SUM(Quantity) AS Sold
FROM Orderrule
GROUP BY ProductID
ORDER BY SUM(Quantity) Desc
```
However that would return all sales, and not just the most sold product (with quantity). | ```
SELECT TOP 1 ProductID, Sold FROM
(
SELECT ProductID, SUM(Quantity) AS Sold
FROM Orderrule
GROUP BY ProductID
) totals
ORDER BY Sold DESC
``` | Try this
```
SELECT TOP(1)
*
FROM
(
Select
ProductID,
MAX(Quantity) As MaxQuantity,
SUM(Quantity) AS Sold
FROM Orderrule
GROUP BY ProductID
)AS X
ORDER BY Sold DESC
``` | SQL Query: SELECT MAX SUM quantity | [
"",
"sql",
""
] |
I don't really know much at all about writing a script for sql and the guy who normally does it is off the next couple of weeks.
I need help trying to write a script that will change the value in a column called "UPDATE\_FLAG" from false to true, wherever "xxx" is present. "xxx" could be in any column, but i need the ... | Since you didn't provide much specific information you'll only get a generalized answer:
```
UPDATE your_table
SET Update_Flag = 1 // this assumes the flag is an integer value
WHERE (column1 = "xxx") // if it's a string do SET Update_Flag = "True"
OR (column2 = "xxx")
OR (column3 = "xxx")
```
etcete... | ```
update table set update_flag=1
where
column1 = 'xxx' or
column2 = 'xxx' or
...
``` | update column_B of specific row that "xxx" is present | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
Please look at the following query:
**tbl\_Contents**
```
Content_Id Content_Title Content_Text
10002 New case Study New case Study
10003 New case Study New case Study
10004 New case Study New case Study
10005 New case Study New case Study
10006 New case Study New case Study
10007 New case S... | Try an [`OUTER APPLY`](https://learn.microsoft.com/en-us/sql/t-sql/queries/from-transact-sql?view=sql-server-ver15)
```
SELECT
C.Content_ID,
C.Content_Title,
C.Content_DatePublished,
M.Media_Id
FROM
tbl_Contents C
OUTER APPLY
(
SELECT TOP 1 *
FROM tbl_Media M
WHER... | You can do this using generic SQL with `group by`:
```
SELECT C.Content_ID, C.Content_Title, MAX(M.Media_Id)
FROM tbl_Contents C LEFT JOIN
tbl_Media M
ON M.Content_Id = C.Content_Id
GROUP BY C.Content_ID, C.Content_Title
ORDER BY MAX(C.Content_DatePublished) ASC;
```
Or with a correlated subquery:
```
SEL... | Left Join without duplicate rows from left table | [
"",
"sql",
"join",
"duplicates",
""
] |
Having a very simple table structure:
```
CREATE TABLE dbo.employees (id int PRIMARY KEY);
CREATE TABLE dbo.assignments (id int PRIMARY KEY, employee_id int );
CREATE TABLE dbo.contracts (id int PRIMARY KEY, assignment_id int );
CREATE TABLE dbo.tasks (id int PRIMARY KEY, contract_id int );
```
Employee -< Assignment... | ```
select id
from employees E
where not exists (
select *
from assignments A
join contracts C on A.ID = C.assignment_id
join tasks T on C.ID = T.contract_id
where A.employee_id = E.id)
``` | You can `inner join` first 3 tables and use `not in` for the 4th.
```
select
e.*
from dbo.employees e
inner join dbo.assignments a on a.employee_id = e.id
inner join dbo.contracts c on c.assignment_id = a.id
where c.id not in (select distinct contract_id from dbo.tasks)
``` | Select rows without nested associated records | [
"",
"sql",
"sql-server",
""
] |
In my Database I have a table called `ARTICLES`. In `ARTICLES` I have **2** columns.


Now I want to get the max value of `NRRENDORDOK` column where the `TIP` column has value **'A'*... | You should take use of the `MAX` function and then GOUP BY tip in order to get the max value for each `tip`:
```
SELECT tip, MAX(nrreddordok) FROM table GROUP BY tip
```
If you just want values for `A` then you can use following query:
```
SELECT MAX(nrreddordok) FROM table WHERE tip = 'A'
``` | ```
SELECT tip, MAX(nrreddordok) FROM table
where tip='A'
GROUP BY tip
``` | How to get max value of a column based on value of another column? | [
"",
"asp.net",
"sql",
"sql-server",
""
] |
So I am trying to pull rows from a table where there are more than one version for an ID that has at least one person for the ID that is not null but the versions that come after it are null.
So, if i had a statement like:
```
select ID, version, person from table1
```
the output would be:
```
ID Version Person
-... | You are seeking all rows where the `person is not null` and that `id` has null rows, and the not null person `version` is less than the null `version` for the same person id:
**Edited predicate based on comment**
```
with sample_data as
(select 1 id, 1 version, 'Tom' person from dual union all
select 1, 2, null f... | I think this query translates pretty nicely into what you asked for?
*List all the rows (R) where the person is null, but only if a previous row (P) with a non-null name exists.*
```
select *
from table1 r
where r.person is null
and exists(
select 'x'
from table1 p
where p.id = r.... | How do I display Rows in a table where all values but the first one for a column is null | [
"",
"sql",
"oracle",
""
] |
Let's say I have some data in a SQL Server database.
```
Location PayID Year
------------------------
Loc1 100 2010
Loc1 100 2011
Loc1 101 2012
Loc2 200 2010
Loc2 201 2011
Loc2 202 2012
```
And I am trying to write a query in SQL Server that will ... | This can be done pretty easily with a recursive CTE:
```
with cte as (
select Location, PayID, PayID as PrevID, Year from payhistory
union all
select p.Location, p.PayID, cte.PayID as PrevID, p.Year
from payhistory p
join cte on cte.Location = p.Location and cte.Year + 1 = p.Year
)
select distinct Location, ... | I didn't see a version specified, so I'd use LAG in 2012. You can filter the results if you want less info. You could replace LAG(PayID,1,NULL) with LAG(PayID,1,PayID) to alter the behavior of the first payid.
```
DECLARE @tbl TABLE (Location VARCHAR(4), PayID INT, Year INT)
INSERT INTO @tbl VALUES
('Loc1',100,2... | How can I generate a previous value table by combining fields from SQL table? | [
"",
"sql",
"sql-server",
""
] |
Despite my little knwoledge of SQL Server, i'm stucked on this problem for a while:
I'm trying to get the final sum of a product of two columns, but SQL Server won't recognize my last column. Here is the query:
```
SELECT
Products.customName AS 'Name',
Ordered_Products.scanned AS 'Sent Quantity',
Charged_Products.pri... | You can do it this way:
```
SELECT
Products.customName AS 'Name',
Ordered_Products.scanned AS 'Sent Quantity',
Charged_Products.price AS 'Product Price',
Ordered_Products.scanned * Charged_Products.price AS 'Charged'
FROM Products
JOIN Charged_Products
ON Products.productsId = Charged_Products.productsId
... | You'd better to do this on client side.
But if you want it so much, then use `GROUPING SETS`.
```
SELECT ISNULL (Products.customName, 'TOTAL') AS 'Name'
, Ordered_Products.scanned AS 'Sent Quantity'
, Charged_Products.price AS 'Product Price'
, SUM (Ordered_Products.scanned * Charged_Products.price) AS 'C... | SQL Server - Get the final sum of a product of two columns | [
"",
"sql",
".net",
"sql-server",
"vb.net",
""
] |
I'm trying to INSERT new row with this values (hotelNo,guestNo,dataform,dataTo,roomNo)
I know the hotel name , so I have to SELECT the hotelNo from another table , it didn't work with me , is there something wrong?
```
INSERT INTO Booking
VALUES (hotelNo,123,'3-sept-1014','3-sept-1014',121)
(SELECT hotelNo
FROM Hotel... | Remove `VALUES (hotelNo,...` from your query and you are good to go.
```
INSERT INTO Booking
(SELECT hotelNo,123,'3-sept-1014','3-sept-1014',121
FROM Hotel
WHERE hotelName='Ritz Carlton' AND city='Dubai')
``` | You should do it without `VALUES`
```
INSERT INTO Booking
(SELECT hotelNo, 123, '3-sept-1014','3-sept-1014',121
FROM Hotel
WHERE hotelName='Ritz Carlton' AND city='Dubai');
``` | SQL , INSERT with SELECT | [
"",
"sql",
"database",
"oracle",
""
] |
Just trying to wrap my head around the logic/commands needed:
I have a contacts table. Each contact has a client in a many-to-one fashion.
I am trying to get any clientIDs where all contacts have a NULL value for email.
Example data:
```
ContactID EmailAddress ClientID
1 NULL 3
907 ... | You can do this with a grouped aggregate and a [`HAVING`](http://technet.microsoft.com/en-us/library/ms180199.aspx) clause (and assuming blank email addresses can be treated the same as nulls):
```
SELECT
ClientID
FROM ClientEmails
GROUP BY ClientID
HAVING MAX(LEN(ISNULL(EmailAddress, ''))) = 0;
```
... | Would this help ?
```
select *
from
(
select clientId,
COUNT(emailAddress) as Mailz,
COUNT(contactId) as Contacts
from contacts
group by clientId
) as src
where (Mailz = 0 and contacts > 0)
``` | TSQL Counting Nulls - where all grouped items have NULL field | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have this query
```
select
raw_item_no,
raw_item_no_2,
raw_item_no_3,
raw_item_no_4
from jtjobfil_sql
where job_no = 213418
```
which outputs like this
```
raw_item_no raw_item_no_2 raw_item_no_3 raw_item_no_4
23 24 25 26
```
how do I get the output to look like ... | You can use `CROSS APPLY`:
```
SELECT x.raw_item_nos
FROM jtjobfil_sql t
CROSS APPLY
(
VALUES
(t.raw_item_no),
(t.raw_item_no_2),
(t.raw_item_no_3),
(t.raw_item_no_4)
) X (raw_item_nos)
WHERE job_no = 213418;
``` | You could do something using a union.
```
with my_query (column1, column2, column3)
as
(
SELECT column1, column2, column3
FROM my_table
where id = 1
)
SELECT column1 FROM my_query
UNION
SELECT column2 FROM my_query
UNION
SELECT column3 FROM my_query
``` | How do I display fields in sql vertically instead of horizontally | [
"",
"sql",
"sql-server-2008-r2",
"unpivot",
""
] |
I have the following tables:
```
create table Users (
Id int
)
create table Vals1 (
UserId int,
Number int
)
create table Vals2 (
UserId int,
Number int
)
```
I have values in `Vals1` and `Vals2` but not a value for every `UserId`. What I want to do is, when available, sum the corresponding values between... | Here is much simpler way of doing it, this will only work if you have 1 row per ID in `Vals1` and `Vals2` table.
```
SELECT id, COALESCE(v1.Number, 0) + COALESCE(v2.Number, 0) as NumberSum
FROM users u
LEFT OUTER JOIN Vals1 AS v1
ON u.id = v1.userid
LEFT OUTER JOIN vals2 AS v2
ON u.id = v2.... | You can use a left join and then account for the nulls with coalesce or isnull
```
SELECT users.id, ISNULL(vals1.number,0) + ISNULL(vals2.number,0) as [sum]
FROM users
left join vals1 on vals1.userid = users.id
left join vals2 on vals2.userid = users.id
``` | Sum Values Between Two Tables | [
"",
"sql",
"sql-server-2008-r2",
""
] |
I have a database where I want to SELECT everything in two columns but exclude all the rows where the value are equal to each other. Is this possible?
Lets say it looks like this:
```
+------------------+------------------+
| Login | Alias |
+------------------+------------------+
| user1@domain... | Try this
```
SELECT *
FROM table_name
WHERE Login <> Alias
``` | ```
select name, Alias,
case
when Login=Alias then 'true'
else 'false'
end
from TableName;
``` | SQL: Exclude row if value in both columns | [
"",
"mysql",
"sql",
""
] |
I am trying out some dynamic SQL queries using R and the postgres package to connect to my DB.
Unfortunately I get an empty data frame if I execute the following statement:
```
x <- "Mean"
query1 <- dbGetQuery(con, statement = paste(
"SELECT *",
"FROM name",
"WHERE statistic = '",x,"'"))
```
I believe that... | Try this:
```
require(stringi)
stri_paste("SELECT * ",
"FROM name ",
"WHERE statistic = '",x,"'",collapse="")
## [1] "SELECT * FROM name WHERE statistic = 'Mean'"
```
or use concatenate operator `%+%`
```
"SELECT * FROM name WHERE statistic ='" %+% x %+% "'"
## [1] "SELECT * FROM name WHERE s... | You should use `paste0` instead of `paste` which is producing wrong results or `paste(..., collapse='')` which is slightly less efficient (see `?paste0` or [docs here](http://stat.ethz.ch/R-manual/R-patched/library/base/html/paste.html)).
Also you should consider preparing your SQL statement in separated variable. In ... | Dynamic SQL Query in R (WHERE) | [
"",
"sql",
"r",
"postgresql",
"dynamic-sql",
""
] |
Is there a query I can run to show currently assigned privileges on a particular schema?
i.e. privileges that were assigned like so:
```
GRANT USAGE ON SCHEMA dbo TO MyUser
```
I have tried
```
SELECT *
FROM information_schema.usage_privileges;
```
but this only returns grants to the built-in PUBLIC role. Instead,... | in console util psql:
```
\dn+
```
will show you
```
Name | Owner | Access privileges | Description
``` | List all schemas with their priveleges for current user:
```
WITH "names"("name") AS (
SELECT n.nspname AS "name"
FROM pg_catalog.pg_namespace n
WHERE n.nspname !~ '^pg_'
AND n.nspname <> 'information_schema'
) SELECT "name",
pg_catalog.has_schema_privilege(current_user, "name", 'CREATE') AS "cre... | postgresql - view schema privileges | [
"",
"sql",
"postgresql",
"amazon-redshift",
""
] |
I have a form where I submit a Start and End date to book of holidays, I then send the value's across to SQL, now i'm a bit stuck because what I need to do is get the dates between the start and end date.
Can anyone help me with this I just need a calculation for my select statement to transfer all the dates between a... | Try this:
```
DECLARE @FromDate datetime
DECLARE @ToDate datetime
SELECT @FromDate=FromDateCol FROM TableName
SELECT @ToDate=ToDateCol FROM TableName
WITH cte AS
(
SELECT CAST(@FromDate AS DATETIME) DateValue
UNION ALL
SELECT DateValue + 1
FROM cte
WHERE DateValue + 1 < @ToDate
)
SELECT DateValue
... | That should not be to difficult to difficult to figure if you are using SQL server! Try this website it is good documentation on how to retrieve those dates that you need.
These are the select statements:
start date (PRSTDATE) and the end date (PRENDATE)
SELECT statement
docs.oracle.com/javadb/10.6.2.1/.../rrefsqlj41... | Select Statement Gathering Dates | [
"",
"date-arithmetic",
"sql",
""
] |
I have this as a result of the query:
```
select cast(to_date(a.start_time,'mm/dd/yyyy hh:mi:ss pm') as timestamp) date_of_call,
ora_rowscn from calling_table a where rownum <= 10;
DATE_OF_CALLING ORA_ROWSCN
26-JUL-13 12.29.28.000000000 PM 8347567733892
26-JUL-13 12.29.35.000000000 PM 8347567733892
2... | You're trying to look too far back. You can only convert to and from SCNs that are in the redo/flashback window maintained by your system. Once changes age out then the mapping is lost.
This is explained [in the documentation](http://docs.oracle.com/cd/E18283_01/server.112/e17118/functions161.htm):
> The association ... | The SCN\_TO\_TIMESTAMP uses some internal algorithms to do the mapping between SCN and TIME when some event happened and it does the job with a good approximation. But there is a limit. You cannot go too far in the past if the UNDO data does not cover your period.
In that case there is a tricky way to create our own m... | How to use Timestamp_to_scn and Scn_to_timestamp in Oracle? | [
"",
"sql",
"oracle",
"datetime",
"timestamp",
"oracle-sqldeveloper",
""
] |
I'am making a report in which I have to find out how many times there has been a situation where one or more row type 1 is found between row type 2 dates. Data looks like this and is sorted by date:
```
Date Row type
2014-01-17 2
2014-01-21 1*
2014-02-06 2
2014-02-11 1*
2014-02-20 1*
2014-03-19... | ```
WITH AllRowNumbers AS (
SELECT RowType
,ROW_NUMBER() OVER (ORDER BY [Date]) AS RowNumber
FROM #T
)
,Type2RowNumbers AS (
SELECT RowNumber
FROM AllRowNumbers
WHERE RowType = 2
)
,Gaps AS (
SELECT RowNumber - ROW_NUMBER() OVER (ORDER BY RowNumber) AS Gap
FROM Type2RowNumbers
)
SE... | Here it is,...
```
;With CTE as
(
select *,Row_number() over (order by dateDt) as RNo
from mtT
)
select COUNT(*) from CTE as a
inner join CTE as b on a.RNo + 1 = b.RNo
and a.rowType <> b.rowType
where a.rowType = 1
``` | Count how many times row type 1 is found between row type 2 dates | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
So I have a history table called `Member_Phys_History` in SQL-Server 2008
Looks like this:
```
RecID, MemberID, Phys_ID, Phys_Start, Phys_End, Phys_Update
```
The first column is `identity`, the `Phys_Start`, `Phys_End`, and `Phys_Update` are dates.
I have another table called `Member_Phys_Update`
```
MemberID, Ph... | Try this
```
Select A.*, B.Phys_End_Date
from table1 A
outer apply (select (min(Phys_Start_Date) - 1) Phys_End_Date from table1 x
where x.Phys_Start_Date > A.Phys_Start_Date
AND X.MemberID = A.MemberID) B
```
[SQL DEMO](http://sqlfiddle.com/#!3/a2c7d3/1)
Edit (Adding Update SQL)
```
update... | As alternative you can do it using Common Table expression.
```
;WITH base
AS (
SELECT *
,ROW_NUMBER() OVER ( PARTITION BY MemberID ORDER BY Phys_Start ASC ) AS rn
FROM Member_Phys_History
),
nextDate
AS (
SELE... | SELECT NEXT ROW, COMPARE, SET PREVIOUS ROW | [
"",
"sql",
"sql-server",
"sql-server-2008",
"conditional-statements",
""
] |
How to convert smalldatetime to varchar? I've tried everything from <http://msdn.microsoft.com/en-us/library/ms187928.aspx>, but it didn't work.
I want to convert smalldatetime into varchar, because I want to use it in select like this:
`select 'Some text'+@Date`
thanks in advance | '121' is the format of the date in this case 'yyyy-mm-dd hh:mi:ss.mmm(24h)',
char(16) is the number of characters you wish to include, first 16 in this case.
```
select 'Some text'+convert(char(16), @date, 121)
```
[Cast and Convert](http://msdn.microsoft.com/query/dev10.query?appId=Dev10IDEF1&l=EN-US&k=k%28CONVERT_T... | SELECT CONVERT(VARCHAR(20), YourDateColumn, 103) as NewColumnName
here 103 make the date format as dd/mm/yyyy
if you want mm/dd/yyyy, you have to use 100 | Converting smalldatetime datatype to varchar datatype | [
"",
"sql",
"sql-server",
""
] |
I have two tables:
* **reports**
* **report\_contents**
which are related by foreign key **content\_id** on **reports** table.
I need to create procedure which delete some reports together with their contents, like this:
```
DELETE FROM report_contents WHERE id IN
(SELECT content_id FROM reports WHERE extra_v... | If the number of ids is relatively small (i.e. just a few hundred or thousand) you can comfortably store the IDs to delete temporarily in a PL/SQL array.
```
PROCEDURE delete_reports (extraValue NUMBER) IS
TYPE id_table IS TABLE OF reports.content_id%TYPE INDEX BY BINARY_INTEGER;
ids id_table;
BEGIN
/* which r... | Since its an `SP`, you could use an intermediate `TABLE` variable to store your results
```
CREATE OR REPLACE PROCEDURE delete_reports (extraValue NUMBER) IS
BEGIN
DECLARE @TABLE table
( CONTENT_ID int)
INSERT INTo @TABLE
SELECT content_id FROM reports WHERE extra_value = extraValue
DELETE FROM r... | Removing records from related tables | [
"",
"sql",
"oracle",
"plsql",
""
] |
I have two queries:
```
SELECT
users.id,
users.gender,
users.status,
users.icon_id,
users.image_name,
coords.lat,
coords.lng,
users.mess_count
FROM
users
INNER JOIN
coords ON users.id = coords.user_id
```
then I select blocked users:
```
SELECT
... | There are several ways to do it, the only mildly compromising factor is that I *believe* you want to exclude users that appear in *either* of two columns in the `blocks` table.
SQL traditionally has weaker performance with `OR` logic, which the following query attempts to work around. *(In part due to its ability to m... | Check this out, I wrote the query using `NOT IN`.
```
SELECT
users.id,
users.gender,
users.status,
users.icon_id,
users.image_name,
coords.lat,
coords.lng,
users.mess_count
FROM
users
INNER JOIN coords ON users.id=coords.user_id
Where
users.id NOT IN (SELECT first_user FROM blocks ... | How to replace 2 queries with except | [
"",
"sql",
"postgresql",
"except",
""
] |
Please help:
I have to create a column based on an expression from other columns,
but before that expression hits, there has to be a date check
if the date is before a specific date- it must do an expression, if the date is after said date, it must do another expression,
THEN: theres a unique column that has the dig... | You need two case statement nested within another case statement, it can be done like following
```
SELECT CASE WHEN date > neededDate THEN
CASE ExpressionColumn
WHEN 1 THEN '1'
WHEN 2 THEN '2'
ELSE 'null'
... | you have your syntax wrong:
```
select case sign(datediff('s', date, neededDate)) -- precision: second
when 0 then -- case missing in your spec !
else
case ExpressionColumn
when 1 then -- case 1
when 2 then -- case 2
else -- ... | SQL INNERJOIN with a switch case and if statement in select | [
"",
"sql",
"sql-server",
""
] |
I am using this query to display a column with money datatype and how could I insert comma on top of this.
```
'$ '+CONVERT(varchar,CONVERT(decimal(10,0), CONVERT(money,B2.Total_Amount)),1) as Total_Amount,
'$ '+CONVERT(varchar,CONVERT(decimal(10,0), CONVERT(money,B2.Monthly_Amount )),1) as Monthly_Amount
```
Output
... | I think you need this
```
'$ '+ Replace(CONVERT(varchar,CAST(B2.Total_Amount AS money),1) ,'.00','') as Total_Amount,
'$ '+ Replace(CONVERT(varchar, CAST(B2.Monthly_Amount As money),1),'.00','') as Monthly_Amount
```
If B2.Monthly\_Amount is
```
1987654321
```
Then the Op will be
```
1,987,654,321
``` | you can achieve this with this:
`select replace(convert(varchar,convert(Money, B2.Total_Amount),1),'.00','')`
BUT YOU SHOULDN'T DO IT
thats part of the display layer | Display comma for column values | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have a dropdown and I want to check the selected value first before I run my SQL command so here is my logic: if the selected value of the dropdown is not `'ALL'` then I want to run this sql statement:
```
select distinct Location
from myTable
where PROGRAM = '"+program+'"
```
else if selected value of the dropdo... | Don't change your SQL command instead create different SQL command's text based on the condition. Also you should use [SqlParameter](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparameter.aspx) instead of string concatenation. Your code is prone to [SQL injection](http://en.wikipedia.org/wiki/SQL_in... | Do this:
```
protected void BindServiceList(DropDownList ddlService)
{
DropDownList ddl = (DropDownList)GV_MJJ.HeaderRow.FindControl("ddlProgram");
string program = ddl.SelectedValue;
String strConnString = System.Configuration.ConfigurationManager
.ConnectionStrings["myConn"].ConnectionStr... | Choose between two SQL statements using CASE or something else | [
"",
"asp.net",
"sql",
"sql-server",
""
] |
I am trying to run a query from sql developer and query has variables (`:var`). I am having problem with the date variables.
I used all the possible combinations to format date using `to_date()` function.
Every time getting below exception:
```
ORA-00932: inconsistent datatypes: expected DATE got NUMBER
00932. 00000 ... | Try changing your query to be:
```
select first_name,
last_name,
dob,
org
from emp
where dob > to_date(:highDate,'DD-MON-YYYY');
```
then when prompted, enter `'20-JAN-2010'`. | Just copying the answer from Oracle Community forum:
> You should be able to enter dates which conform to your
> `NLS_DATE_FORMAT` setting.
>
> e.g. If `NLS_DATE_FORMAT` is `DD-MON-YYYY`, you can enter
> `24-jan-2011` for today's date.
Worked for me. | How to use date variable in sql developer's "Enter Binds" dialog? | [
"",
"sql",
"oracle",
"oracle-sqldeveloper",
""
] |
I had a table named `movies` which had the fields `id` as primary key, and two varchars: `title` and `genre`.
I created a new table named `genres` with the int field `id` as primary key and `desription` varchar. I changed the field `genre` in my `movies` table so I could create a foreign key referencing a genre.
Howe... | clear your table contents and try adding foreign key.
if your table contain data which not matching the foreign key field value you will see this error ... | It looks like your table `movies` has data in genre column which is not present in genres.id column.
Your statement should work after removing the invalid data.
Hope it helps
Vishad | Error when adding foreign key | [
"",
"mysql",
"sql",
"database",
"mysql-workbench",
""
] |
i have below string.Can some one help me how to select only characters after **`data/`** and before **`cross/`**
```
/dss/data/20131223_155909_7325/Cross-Boundary-Collaboration_Participant_Workbook_v1.4.onepkg
```
Please note **`/dss/data/`** will be consistent but characters may vary after **`7325/`** | This will select everything after `/dss/data/` up to next slash `/`
```
DECLARE @string NVARCHAR(MAX);
SET @string = '/dss/data/20131223_155909_7325/Cross-Boundary-Collaboration_Participant_Workbook_v1.4.onepkg';
SELECT LEFT(REPLACE(@string,'/dss/data/',''), CHARINDEX('/',REPLACE(@string,'/dss/data/',''))-1)
```
`20... | USE [CHARINDEX and then SUBSTRING](http://social.technet.microsoft.com/wiki/contents/articles/17948.t-sql-right-left-substring-and-charindex-functions.aspx)
EDIT:
This will give you an idea on what to do:
```
DECLARE @URL VARCHAR(1000)
SET @URL = 'http://www.sql-server-helper.com/tips/tip-of-the-day.aspx?tid=58'
... | Select character in between slashes --sql | [
"",
"sql",
"sql-server",
""
] |
I have a table which has below structure. I'm using phpmyadmin 3.4.5, mysql version 5.5.16.
**Table**
```
Invoice_ID - PO_ID- Product - Quantity Invoice_Qty - Amount
Inv1 - PO1 - P1 - 100 - 50 - 1000
Inv2 - PO1 - P1 - 100 - 50 - 1000
Inv3 - PO2 - P2 ... | Your sqlfiddle was confusing. Please don't provide sample data here and then use different sample data in the sqlfiddle. And your desired result here is wrong, since you said in the description
> If Previous Row of PO\_ID and and Product Name is Same as current Row PO\_ID and Product then Quantity of current row shoul... | this works :):) :
```
select Invoice_ID,PO_ID,product,
case when
decode(lead(Quantity) over (order by PO_ID),Quantity,'SAME','DIFF') = 'SAME'
then Quantity
else 0
end Quantity, Amount
from <table-name>
``` | Change Value based on previous rows in mysql | [
"",
"mysql",
"sql",
"stored-procedures",
"lag",
""
] |
I have inherited a codebase in Web forms and are having trouble with a SQL query.
```
SELECT foretag.namn, foretag.epost, foretag.forlangEj, service_fakturering.*
FROM foretag
INNER JOIN service ON foretag.id = service.foretagsid
INNER JOIN service_fakturering ON service.id = service_fakturering.service_id
WH... | Using [`ROW_NUMBER()`](http://technet.microsoft.com/en-us/library/ms186734.aspx) function, along with [common table expression](http://technet.microsoft.com/en-us/library/ms190766%28v=sql.105%29.aspx), it can be done like this:
```
WITH cte_service_fakturering AS
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY service... | The Sub select will group your service\_fakturering rows and get the maxId for you. This is then used to join back into your query and filter for only those rows you are interested in.
```
SELECT foretag.namn, foretag.epost, foretag.forlangEj, service_fakturering.*
FROM foretag
INNER JOIN service ON foretag.id = ser... | Select the highest Id Where serviceId occurs more than once | [
"",
"sql",
"sql-server",
""
] |
I need an algorithm for calculating the number of the day of the week in the month. Like 1st Friday of the month, 3rd Monday of the month, etc.)
Any ideas are appreciated.
Here is the final result:
```
declare @dt date = GetDate()
declare @DayOfWeek tinyint = datepart(weekday,@dt)
declare @DayOfMonth smallint = da... | Followint code will give you `1st Wednesday of April 2014` for today:
```
SELECT cast((DATEPART(d, GETDATE() - 1) / 7) + 1 as varchar(12))
+ 'st ' + DATENAME(WEEKDAY, getdate()) + ' of ' +
DATENAME(month, getdate()) + ' ' + DATENAME(year, getdate());
```
For any date use the code below. It gives `5th Tuesday of Apri... | Okeeeey my tuuuurn ,
Please rate my answer Metaphor hhh, Here's the cooode :
```
declare @v_month nvarchar(2) = '04'
,@v_annee nvarchar(4) = '2014'
declare @v_date date = convert(date,@v_annee+'-'+@v_month+'-01')
declare @v_date_2 date = dateadd(M,1,@v_date)
if OBJECT_ID('temp') is not null
drop table ... | Get day of the week in month (2nd Tuesday, etc.) | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I'm struggle with a SQL join for parent client records (literally in my example!). My db tables are made up of something like (excuse the very generic example).
```
Table Room
Room No
1
2
3
Table Customer
| Customer ID | Customer Name | Associated
| 1 | Joe Bloggs |
| 2 | ... | You should be able to do this using a recursive [CTE](http://technet.microsoft.com/en-us/library/ms190766%28v=sql.105%29.aspx).
Something like below
```
;WITH Vals AS (
SELECT CustomerID,
CustomerName,
b.Room
FROM Customer c INNER JOIN
Bookings b ON... | ```
;with Cte (RoomId,Name ,CustomerId)
as(
Select R.RoomId,C.Name,C.CustomerId
From Booking B
Inner Join Customer C on C.CustomerId=B.Customer
Inner Join Room R On R.RoomId=B.RoomNo
Union All
Select Cte.RoomId,Cus.Name,Cus.CustomerId
From Customer Cus
inner join Cte On Cte.Customer... | SQL Join for child records | [
"",
"sql",
"sql-server",
""
] |
I have the below table. the only difference in data is **suff, wt**; the rest of them look the same.
Things table
```
Prefix Baseletter suff CSCcode Description WT BNO BNO-CSCcode
EIGC A5560 BGA 04020 blah1 0 5560 5560-04020
EIGC A5560 HEA 04020 ... | `BNO-CSCcode` contains duplicates. You are joining the first record of `Things` to both records of `Mapp`, then the second record of `Things` joins to both records of `Mapp`. Giving you a total of 4 records.
If you want to join these together, you need some unique way of identifying the rows between the tables.
A Dis... | You are getting duplicates because both records in the `Things` table have a `BNO-CSCcode` of 5560-04020, as do both records in the `Mapp` table. The only distinction between the two that I can see is the `Description` field. So, if you use the following query:
```
SELECT Things.Prefix ,Things.Baseletter,Things.suff,T... | Inner join returning duplicate records access sql | [
"",
"sql",
"ms-access",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.