我有一个表格,其中根据下面的示例记录为特定的ID存储了多个记录
样本记录
ID Note Date Tag
2 A2 05-07-2019 1
3 A3 05-07-2019 0
2 A4 08-07-2019 0
2 A5 09-07-2019 1
3 A6 10-07-2019 0
3 A7 11-07-2019 0
3 A8 12-07-2019 0
3 A9 13-07-2019 0
2 A10 14-07-2019 0
3 A11 15-07-2019 1
3 A12 16-07-2019 1
2 A13 17-07-2019 0
现在我想要的是
获取特定ID的最新记录
获取特定ID的最新记录,其中tag = 1
第2点的先前记录
结果
Column1 Column2 Column3 Column4
(ID) (LatestFUNote) (PreviousFUNoteofColumn4) (Latest FU Note Where Tag=1)
2 A13 A4 A5
3 A12 A11 A12
答案 0 :(得分:2)
with cte as
(
select
ID
, Note
, Date
, Tag
,lag(note) over (order by [date] ) prevnote
, row_number() over (partition by [ID] order by [date] desc) rn1
, row_number() over (partition by [ID],Tag order by [date] desc) rn2
from
(values
(2, 'A2', '2019-07-05', 1)
,(3, 'A3', '2019-07-05', 0)
,(2, 'A4', '2019-07-08', 0)
,(2, 'A5', '2019-07-09', 1)
,(3, 'A6', '2019-07-10', 0)
,(3, 'A7', '2019-07-11', 0)
,(3, 'A8', '2019-07-12', 0)
,(3, 'A9', '2019-07-13', 0)
,(2, 'A10', '2019-07-14', 0)
,(3, 'A11', '2019-07-15', 1)
,(3, 'A12', '2019-07-16', 1)
,(2, 'A13', '2019-07-17', 0)
) a(ID , Note , Date , Tag)
)
select
[ID]
,max(iif(rn1=1,Note,null)) LatestFUNote
,max(iif(rn2=1 and [tag]=1,prevnote,null)) PreviousFUNoteofColumn4
,max(iif(rn2=1 and [tag]=1,Note,null)) [Latest FU Note Where Tag=1]
from CTE group by [ID]