TSQL制作不起作用

时间:2013-09-21 17:14:00

标签: sql sql-server tsql

我有如下数据

Id , TagNo , Revision
100 , 20001 , A
101 , 20001 , B
102 , 20001 , C
103 , 20002 , B
104 , 20002 , A
105 , 20003 , B

我希望如果我通过B进行修订我有以下记录

101 , 20001 , B
103 , 20002 , B
105 , 20003 , B

如果我通过A进行修订,我应该有以下记录

100 , 20001 , A
104 , 20002 , A

如果我通过C进行修订,以下应该是我的结果

102 , 20001 , C
103 , 20002 , B
105 , 20003 , B

我无法用TSQl制作它,任何身体能帮助我吗? 谢谢

3 个答案:

答案 0 :(得分:2)

with cte as (
    select
        Id, TagNo, Revision,
        row_number() over(partition by TagNo order by Revision desc) as rn
    from Table1
    where Revision <= @Revision
)
select Id, TagNo, Revision
from cte
where rn = 1

<强> sql fiddle demo

答案 1 :(得分:0)

您是否只是在寻找

select * from mytable where Revision = 'A'

select * from mytable where Revision = 'B'

select * from mytable where Revision = 'C'

答案 2 :(得分:0)

;WITH TagGroups as
(
  SELECT
    [TagNo],
    MAX([Revision]) as [Revision]
  FROM Tags
  WHERE [Revision] <= 'A' -- Revision for pass
  GROUP BY [TagNo]
)
SELECT
  t.[ID],
  t.[TagNo],
  t.[Revision]
FROM TagGroups tg
JOIN Tags t
  ON t.[TagNo] = tg.[TagNo]
  AND t.[Revision] = tg.[Revision]
ORDER BY t.[ID]