大家好我需要显示一些报告,但我没有这个结果的解决方案。 请帮我指导查询此结果的解决方案。
这是我的表(日志)
我需要编写SQL查询来生成以下结果:
请指导我, 谢谢你的所有答案。
答案 0 :(得分:0)
这是一个Island and Gaps问题,可以使用ROW_NUMBER
:
;WITH Cte AS(
SELECT *,
grp = ROW_NUMBER() OVER(PARTITION BY NODE, STATUS ORDER BY DATE_TIME)
- ROW_NUMBER() OVER(PARTITION BY NODE, STATUS, VALUE ORDER BY DATE_TIME)
FROM [Log]
),
CteMinMax AS(
SELECT
NODE,
STATUS,
VALUE,
MIN_DATE_TIME = MIN(DATE_TIME),
MAX_DATE_TIME = MAX(DATE_TIME)
FROM Cte
GROUP BY
NODE, STATUS, VALUE, grp
)
SELECT
NODE,
STATUS,
VALUE,
[Begin Failed] = cmm.MIN_DATE_TIME,
[Last OK] = x.MIN_DATE_TIME,
[Time/Minute] = DATEDIFF(MINUTE, cmm.MIN_DATE_TIME, x.MIN_DATE_TIME)
FROM CteMinMax cmm
CROSS APPLY(
SELECT TOP 1 MIN_DATE_TIME
FROM CteMinMax
WHERE
NODE = cmm.NODE
AND STATUS = cmm.STATUS
AND VALUE = 0
AND MIN_DATE_TIME > cmm.MIN_DATE_TIME
) x
WHERE cmm.VALUE = 1
<强> RESULT 强>
| NODE | STATUS | VALUE | Begin Failed | Last OK | Time/Minute |
|------|----------------|-------|----------------------------|----------------------------|-------------|
| A | SQL Connection | 1 | December, 02 2015 14:02:00 | December, 02 2015 14:04:00 | 2 |
| A | SQL Connection | 1 | December, 02 2015 14:05:00 | December, 02 2015 14:08:00 | 3 |
| A | SQL Connection | 1 | December, 02 2015 14:12:00 | December, 02 2015 14:15:00 | 3 |
| A | SQL Connection | 1 | December, 02 2015 14:17:00 | December, 02 2015 14:18:00 | 1 |