用例来选择多个条件

时间:2016-11-18 15:00:57

标签: sql sql-server

这是我的SQL表

RecordID      RecordState     Time
-----------------------------------
record1       failed          9:10
record2       failed          9:20
record2       passed          9:30

这是我的查询。

select RecordID, max(RecordState)
from RecordTable a
group by RecordID

对于记录record2,该值首先失败然后传递,因此传递此记录的max(recordstate)

RecordID      RecordState     Time
-----------------------------------
record1       failed          9:10
record2       passed          9:30

现在这是一个不同的场景

  RecordID      RecordState     Time
-----------------------------------
record1       failed          9:10
record2       failed          9:20
record2       passed          9:30
record2       failed          9:40

在9:40,记录再次失败,所以我的最终输出应该是

RecordID      RecordState     Time
-----------------------------------
record1       failed          9:10
record2       failed          9:40

然而,由于我使用Max(RecordState),它将始终返回'传递'我需要以某种方式检查最新时间并在这种情况下显示失败(9:40)。

2 个答案:

答案 0 :(得分:4)

使用ROW_NUMBER()order by Time DESC

<强> SQL DEMO

SELECT RecordID, RecordState, Time
FROM ( SELECT RecordID, RecordState, Time,
              ROW_NUMBER() over (PARTITION BY RecordID      
                                 ORDER BY Time DESC) as rn
       FROM YourTable
      ) T
WHERE T.rn =1

<强>输出

enter image description here

答案 1 :(得分:0)

这将计算具有相同单元格的行,然后将最后一行计入日期

select * from  
(
select *,
       row_number()over(partition by RecordID order by time desc) as rn 
from RecordTable
) A
Where RN = 1 and RecordState = 'Failed'