我正在尝试编写一个SQL Server查询,其中特定ID可以有多个修订,但我只想提取起始状态和当前/结束状态。我不一定关心沿途发生的事情。
以下是当前数据库结构的示例(我不能假设数据将被排序)。
ID REV STATUS CURRENT NOTES
----------------------------------------------
1111 1 High F Note One
1111 2 High F Note Two
1111 3 Medium F Note Three
1111 4 Medium F Note Four
1111 5 Medium F Note Five
1111 6 Medium F Note Six
1111 7 Complete T Note Seven
2222 1 Medium F Note One
2222 2 High F Note Two
2222 3 Complete T Note Three
3333 1 Low T Note One
4444 1 Low F Note One
4444 2 Medium T Note Two
这是我想要的输出。
ID START STATUS END STATUS END NOTE
---------------------------------------------------
1111 High Complete Note Seven
2222 Medium Complete Note Three
3333 Low Low Note One
4444 Low Medium Note Two
非常感谢任何帮助。
答案 0 :(得分:5)
起初我以为你只想要第一行和最后一行而且我没有注意到current
列......
select * from
(
select *
row_number() over (partition by id order by rev asc) rnA,
row_number() over (partition by id order by rev desc) rnD
from <table> revs
) r
where rnA = 1 or rnD = 1
实际上在仔细阅读问题之后......
select
id,
min(case when rev = 1 then status end) as "Start Status",
min(case when current = 'T' then status end) as "End Status",
min(case when current = 'T' then status end) as "End Note"
from <table> rev
group by id
答案 1 :(得分:0)
您似乎只需要获取当前修订版的所有行,然后添加第一个修订版的状态。这是一种方式:
SELECT ID,
(SELECT [STATUS] FROM MyTable t2 WHERE t2.ID = MyTable.ID AND t2.REV = 1) AS [START STATUS],
[STATUS] AS [END STATUS], NOTES AS [END NOTE]
FROM MyTable
WHERE [CURRENT] = 'T'
您也可以加入第一个修订版:
SELECT ID,
Rev1.[STATUS] AS [START STATUS],
[STATUS] AS [END STATUS], NOTES AS [END NOTE]
FROM MyTable
INNER JOIN MyTable Rev1
ON MyTable.ID = Rev1.ID
AND Rev1.REV = 1
WHERE MyTable.[CURRENT] = 'T'
答案 2 :(得分:0)
select ID,
iif(REV=1,STATUS,null) [START STATUS],
iif(maxrev is null,null,STATUS) as [END STATUS],
iif(maxrev is null,null,NOTES) as [END NOTE]
from <tablename,,> t1
left join (select ID, max(REV) maxrev from <tablename,,> group by ID) t2
on t1.ID=t2.ID and t1.rev=t2.maxrev
group by ID,
[START STATUS],
[END STATUS],
[END NOTE]