SQL Server : select where row was X but is not now X - sql

I have a table like this:
WOTranID WOID Status DateCreated
----------------------------------------------
1 5 Ready 6/6/2015
2 5 Pending 6/5/2015
3 7 Pending 6/9/2015
4 8 Scheduled 6/10/2015
What I need is to select all WOID where the status was pending but is not currently pending.
Thank you for your help.
Edit: Using the example table above I would only like to return WOID 5.

First, select all WOIDs which have had a status of pending, then intersect that with the list of WOIDs whose current status is not pending (using row_number() to select the latest status per WOID).
(Select Distinct WOID
from MyTable
where Status = 'Pending')
intersect
(Select WOID
from
(Select WOID
, Status
, Row_number() over (partition by WOID order by DateCreated desc) as RN
from MyTable) a
where Status <> 'Pending' and RN = 1)

May be this:
select distinct t1.WOID
from TableName t1
where Status <> 'Pending' and
not exists(select * from TableName t2
where t2.WOID = t1.WOID and t2.DateCreated > t1.DateCreated) and
exists(select * from TableName t3
where t3.WOID = t1.WOID and t3.DateCreated < t1.DateCreated and t3.Status = 'Pending')

This answer assumes that you want the next woid that changes from pending. If you want all of them, then you should clarify the question.
In SQL Server 2012+, you can use the lag() function:
select t.*
from (select t.*,
lag(status) over (partition by woid order by datecreated) as prev_status
from table t
) t
where prev_status = 'Pending' and status <> 'Pending';
You can do something similar in earlier versions use cross apply.

Related

Postgresql combine IN with NOT IN

I have a table of entities where each can have different statuses. For the sake of keeping history, each status change is reflected by a new row.
Example:
Entity Id Status
123456 1
123456 2
789000 1
Assuming i want to find all rows that have only status 1 (so if they have other statuses they should not be returned), How do I do that?
This query:
select entityid
from tablename
group by entityid
having min(status) = 1 and max(status) = 1
returns all the entityids that you want, so you can use it with the operator IN:
select * from tablename
where entityid in (
select entityid
from tablename
group by entityid
having min(status) = 1 and max(status) = 1
)
Just use not exists:
select t.*
from t
where not exists (select 1
from t t2
where t2.entity_id = t.entity_id and t2.status <> 1
);

Update table set column = case when there is a duplicate found

I want to update a column in a table that would set to plus 1 if it can find a duplicate number in the column cownnum and else it would set to 1 if no duplicate was found
I tried the code below but show error
Msg 512, Level 16, State 1, Line 53
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
The statement has been terminated.
update dbo.temp1 set SEQNO = case SEQNO when (SELECT
cownnum
FROM
dbo.temp1
GROUP BY
cownnum
HAVING
COUNT(*) > 1) then SEQNO = 2 else SEQNO = 1 end
for example the result would be
cownnum 1 1 2 3
SEQNO 1 2 1 1
Your question is confusing, but there's no reason to use the GROUP BY clause:
UPDATE dbo.temp1 SET SEQNO = 1 WHERE SEQNO = cownnum
or perhaps you need to check cownnum somehow:
UPDATE dbo.temp1 SET SEQNO = 1 WHERE cownnum = (SELECT TOP 1 xxx FROM table WHERE ???)
Please provide an example of your data and the expected results.
You can use ROW_NUMBER.
UPDATE t1
SET t1.SEQNO = t2.rowno
FROM table_with_duplicates t1
INNER JOIN
(
SELECT unique_id,
ROW_NUMBER() OVER (PARTITION BY cownnum ORDER BY cownnum) AS rowno
FROM table_with_duplicates
) t2
ON t1.unique_id = t2.unique_id;
The perfect solution for your requirement is
UPDATE #Temp1
SET SEQNO = B.NewSEQ
FROM #Temp1 A ,
( SELECT id,
CASE WHEN COWNNUM = LAG(COWNNUM) OVER ( ORDER BY id ) THEN
ROW_NUMBER() OVER ( PARTITION BY COWNNUM ORDER BY id ) ELSE 1 END AS NewSEQ
FROM #temp1
) B
WHERE A.id = B.id
you can check this query execution by clicking on DEMO
You can use lag() to check previous row value in sqlserver
Update temp1
set temp1.SEQNO = B.SEQNO
FROM temp1 A, (select id , COWNNUM,
case when COWNNUM = lag(COWNNUM) over(order by id)
then ROW_NUMBER() OVER ( PARTITION BY COWNNUM ORDER BY id ) else 1 end as SEQNO
from temp1) B
WHERE A.id = B.id
DEMO
You can use window functions. This is simplest using an updatable CTE:
with toupdate as (
select t.*,
row_number() over (partition by cownum order by (select null)) as new_seqno
from dbo.temp1 t
)
update toupdate
set seqno = new_seqno;
If I understand the question correctly, no join is required.

SQL Query If Condition for specific text within two rows

I need to write a query, but I'm not exactly sure how to write it. I need to grab all the EmployeeIds based off the status. If it is completed and pending, completed takes precedence. However, if there is only pending and not completed I'll take pending, else don't take any of the rows for that employee. I just need one item per EmployeeId. Technically I would also need to grab the earliest date but I think I would know how to write that part.
RowNumber Status EmployeeId Produce Date
-------------------------------------------------------
1 New 1 Apples 1/1/18
2 Pending 1 BlueBerry 1/2/18
3 New 1 Oranges 1/3/18
4 Pending 2 Bananas 1/1/18
5 New 2 Grapes 1/2/18
6 Complete 2 Limes 1/3/18
So in this example I need the following below
RowNumber Status EmployeeId Produce Date
--------------------------------------------------------
2 Pending 1 BlueBerry 1/2/18
6 Complete 2 Limes 1/3/18
The hardest part for me is trying to figure out how to compare strings. Basically (semi pseudo-code)
Select top 1
t.EmployeeId, t.Produce, t.Date, stat.Status
(Case
If t.Status = 'Complete'
Select 'Complete'
If t.Status = 'Pending'
Select 'Pending'
Else
Dont Add this row ) stat
From
Table t
Where
t.Status = 'Complete' or t.Status = 'Pending'
Order by
t.Date
There's at least two different approaches coming to my mind :
SELECT DISTINCT EmployeeId
FROM Table
WHERE Status = "Complete"
UNION
SELECT DISTINCT t1.EmployeeId
FROM Table t1
LEFT OUTER JOIN Table t2
ON t2.EmployeeId = t1.EmployeeId
AND t2.Status = "Complete"
WHERE t1.Status = "Pending"
AND t2.Status IS NULL
… or using coalesce() if your database engine supports it:
SELECT DISTINCT pend.EmployeeId,
coalesce(comp.Status,pend.Status),
coalesce(comp.RowNumber,pend.RowNumber)
FROM MyTable pend
LEFT OUTER JOIN MyTable comp
ON comp.EmployeeId = pend.EmployeeId
AND comp.Status = 'Complete'
WHERE pend.Status IN ('Complete','Pending');
Is this what you want using row_number() :
select top (1) with ties *
from table t
where Status in ('Completed', 'Pending')
order by row_number() over (partition by EmployeeId
order by (case Status when 'Completed'
then 0
when 'Pending'
then 1
end)
);
You could do this with a UNION ALL coupled with a WHERE NOT EXISTS:
SELECT t1.*
FROM [Table] t1
WHERE [Status] = 'Completed'
UNION ALL
SELECT t2.*
FROM [Table] t2
WHERE [Status] = 'Pending'
AND NOT EXISTS (
SELECT 1
FROM [Table]
WHERE EmployeeId = t2.EmployeeId
AND [Status] = [Completed]
);
You could calculate a ROW_NUMBER that uses a CASE WHEN.
And then filter on that.
For example:
SELECT RowNumber, [Status], EmployeeId, Produce, [Date]
FROM
(
SELECT
RowNumber, [Status], EmployeeId, Produce, [Date],
ROW_NUMBER() OVER (
PARTITION BY EmployeeId
ORDER BY [Date] DESC,
CASE [Status] WHEN 'Complete' THEN 1 WHEN 'Pending' THEN 2 ELSE 9 END
) AS RN
FROM [YourTable] t
WHERE [Status] IN ('Complete','Pending')
) q
WHERE RN = 1
ORDER BY EmployeeId

Find the latest 3 records with the same status

I need to find the latest 3 records for each user that has a particular status on 'Fail'. At first it seems easy but I just can't seem to get it right.
So in a table of:
ID Date Status
1 2017-01-01 Fail
1 2017-01-02 Fail
1 2017-02-04 Fail
1 2015-03-21 Pass
1 2014-02-19 Fail
1 2016-10-23 Pass
2 2017-01-01 Fail
2 2017-01-02 Pass
2 2017-02-04 Fail
2 2016-10-23 Fail
I would expect ID 1 to be returned as the most recent 3 records are fails, but not ID 2, as they have a pass within their three fails. Each user may have any number of Pass and Fail records. There are thousands of different IDs
So far I've tried a CTE with ROW_NUMBER() to order the attempts but can't think of a way to ensure that the latest three results all have the same status of Fail.
Expected Results
ID Latest Fail Date Count
1 2017-02-04 3
Maybe try something like this:
WITH cte
AS
(
SELECT id,
date,
status,
ROW_NUMBER () OVER (PARTITION BY id ORDER BY date DESC) row
FROM #table
),cte2
AS
(
SELECT id, max(date) as date, count(*) AS count
FROM cte
WHERE status = 'fail'
AND row <= 3
GROUP BY id
)
SELECT id,
date AS latest_fail,
count
FROM cte2
WHERE count = 3
Check This.
Demo : Here
with CTE as
(
select *,ROW_NUMBER () over( partition by id order by date desc) rnk
from temp
where Status ='Fail'
)
select top 1 ID,max(DATE) as Latest_Fail_Date ,COUNT(rnk) as count
from CTE where rnk <=3
group by ID
Ouptut :
I think you can do this using cross apply:
select i.id
from (select distinct id from t) i cross apply
(select sum(case when t.status = 'Fail' then 1 else 0 end) as numFails
from (select top 3 t.*
from t
where t.id = i.id
order by date desc
) ti
) ti
where numFails = 3;
Note: You probably have a table with all the ids. If so, you an use that instead of the select distinct subquery.
Or, similarly:
select i.id
from (select distinct id from t) i cross apply
(select top 3 t.*
from t
where t.id = i.id
order by date desc
) ti
group by i.id
having min(ti.status) = 'Fail' and max(ti.status) = 'Fail' and
count(*) = 3;
Here you go:
declare #numOfTries int = 3;
with fails_nums as
(
select *, row_number() over (partition by ID order by [Date] desc) as rn
from #fails
)
select ID, max([Date]) [Date], count(*) as [count]
from fails_nums fn1
where fn1.rn <= #numOftries
group by ID
having count(case when [Status]='Fail' then [Status] end) = #numOfTries
Example here

Classic ASP / MSSQL - Remove returned results based on certain conditions

I have a little sql query, like so
SELECT * FROM table
This returns a bunch of results, i output the following fields:
ID
UserID
Amount
Date
What i want to do is get the most recent entry from each UserID ( based on ID ), then if the amount is 0 do not return ANY results from that UserID.
select t1.*
from your_table t1
join
(
select userid, max(date) as mdate
from your_table
group by userid
having sum(case when amount = 0 then 1 else 0 end) = 0
) t2 on t1.userid = t2.userid and t1.date = t2.mdate
In the subquery you group by the user and select only those having no amount of zero. In that select you use max(date) as mdate to get the latest date for each user.
That subquery can be joined to the original table to get the complete record and not just the userid.
try this
WITH cte AS
(
SELECT
MAX(ID) OVER (PARTITION BY UserID) MaxIDForUserID,
ROW_NUMBER() OVER (PARTITION BY UserID ORDER BY ID DESC) rn,
UserID,
Amount,
Date
FROM TableName
)
SELECT * FROM cte WHERE rn = 1 AND Amount != 0