给定临时表#RawAlarms中的以下数据集:
我需要返回每个AlarmState =' UNACK_ALM'的第一个实例,内联下一个AlarmState的实例' ACK_ALM' OR' ACK_RTN'但不是两个。
我正在运行的查询如下:
SELECT RA1.TagName, RA1.DateTime, RA1.Description, RA2.Description, MIN(RA2.DateTime) as AckDT
FROM #RawAlarms RA1
INNER JOIN #RawAlarms RA2 ON RA1.TagName = RA2.TagName AND RA2.DateTime > RA1.DateTime
AND RA1.LotStartDT = RA2.LotStartDT and RA1.LotEndDT = RA2.LotEndDT
WHERE RA1.AlarmState = 'UNACK_ALM' AND RA2.AlarmState IN('ACK_RTN','ACK_ALM')
GROUP BY RA1.TagName, RA1.DateTime, RA1.Description, RA2.Description
ORDER BY RA1.TagName, RA1.DateTime
这些是我得到的结果;以红色突出显示的是我需要的结果示例: 帮助
答案 0 :(得分:1)
我认为APPLY operator可以在这里提供帮助:
SELECT RA1.TagName, RA1.DateTime, RA1.Description, NextAlarmState.Description, NextAlarmState.DateTime AS AckDT
FROM #RawAlarms RA1
CROSS APPLY (SELECT TOP 1 RA2.Description, RA2.DateTime
FROM #RawAlarms RA2
WHERE RA2.LotStartDT = RA1.LotStartDT
AND RA2.LotEndDT = RA1.LotEndDT
AND RA2.DateTime > RA1.DateTime
AND RA2.AlarmState IN ('ACK_RTN', 'ACK_ALM')
ORDER BY RA2.DateTime) AS NextAlarmState
WHERE RA1.AlarmState = 'UNACK_ALM'
ORDER BY RA1.TagName, RA1.DateTime