Reputation: 25
I have an issue in getting the required output for below scenario.
name | provider | visit_dt | rd | rn
A | 100000 | 06/05/'17 | 1 | 1
A | 100001 | 06/04/'17 | 1 | 0
A | 100001 | 06/03/'17 | 1 | 0
B | 100000 | 06/05/'17 | 1 | 0
B | 100001 | 06/05/'17 | 1 | 1
C | 100000 | 06/05/'17 | 1 | 0
C | 100001 | 06/04/'17 | 1 | 0
C | 100001 | 06/03/'17 | 1 | 1
D | 100001 | 06/05/'17 | 1 | 0
D | 100001 | 06/04/'17 | 1 | 0
There are 4 different scenarios here:
So the expected output should be as below.
name | provider | visit_dt | rd | rn
A | 100000 | 06/05/'17 | 1 | 1
B | 100000 | 06/05/'17 | 1 | 0
B | 100001 | 06/05/'17 | 1 | 1
C | 100001 | 06/03/'17 | 1 | 1
D | 100001 | 06/05/'17 | 1 | 0
It would be great if anyone could help me to solve this issue.
Any suggestion would be appreciable.
Thank you in advance.
Upvotes: 1
Views: 54
Reputation: 13969
Looks like you have some contradictory conditions here is my approach:
Select * from (
Select *, Con1 = Row_Number() over(Partition by [name] order by visit_dt desc) ,
Con2 = Row_Number() over(partition by [name],[rn] order by visit_dt desc)
from yourVisits
) a
Where (a.Con1 = 1 and rd =1 and rn = 1)
or (a.Con2 = 1 and rn=1)
or (a.Con2 = 1 and rn=0)
Upvotes: 0
Reputation: 4786
If this is SQL 2008+, I believe this will work (as long as visit_dt is a date datatype).
WITH cte1 AS (
SELECT name, provider, visit_dt, rd, rn, DENSE_RANK() OVER (PARTITION BY name ORDER BY visit_dt DESC) AS thisrow
FROM t
)
SELECT *
FROM cte1
WHERE thisrow =1
http://dbfiddle.uk/?rdbms=sqlserver_2014&fiddle=1dc1bf626aed520d601fe68f1f11be55
Upvotes: 1