您好以下案例有问题。 我有一张表"应用程序日志"如
App_name date status
Application 1 10-MAR-17 SUCCEEDED
Application 1 11-MAR-17 SUCCEEDED
Application 1 12-MAR-17 FAILED
Application 1 13-MAR-17 SUCCEEDED
Application 1 14-MAR-17 SUCCEEDED
Application 1 15-MAR-17 FAILED
Application 1 16-MAR-17 SUCCEEDED
Application 1 17-MAR-17 SUCCEEDED
Application 1 18-MAR-17 FAILED
Application 1 19-MAR-17 SUCCEEDED
Application 1 20-MAR-17 SUCCEEDED
Application 1 21-MAR-17 FAILED
Application 1 22-MAR-17 SUCCEEDED
Application 1 23-MAR-17 SUCCEEDED
Application 1 25-MAR-17 SUCCEEDED
Application 3 20-MAR-17 FAILED
Application 3 21-MAR-17 FAILED
Application 3 22-MAR-17 FAILED
Application 3 23-MAR-17 FAILED
Application 3 24-MAR-17 FAILED
我必须找到' n'一个application_name的后续失败状态并将其作为结果返回。例如,如果n = 5,我的查询必须返回app_name = Application 3。
答案 0 :(得分:2)
以下查询适用于SQL Server。我也没有看到为什么它也不应该在Oracle中工作的原因:
SELECT [App_name]
FROM (
SELECT [App_name], [date], [status],
ROW_NUMBER() OVER (PARTITION BY App_name ORDER BY [date])
-
ROW_NUMBER() OVER (PARTITION BY App_name,
CASE
WHEN status = 'FAILED' THEN 1
ELSE 2
END
ORDER BY [date]) AS grp
FROM ApplicationLog) AS t
WHERE status = 'FAILED'
GROUP BY [App_name], grp
HAVING COUNT(*) >= 5
答案 1 :(得分:1)
这是另一种仅使用单个OLAP函数的方法:
SELECT App_name, Max(date) AS LastFail
FROM
(
SELECT App_name, date, status,
-- check if the last 5 rows only contain FAILED
Min(CASE WHEN status = 'FAILED' THEN 1 ELSE 0 end)
Over (PARTITION BY App_name
ORDER BY date
-- caution, as this includes the current row it must be n-1
ROWS 4 Preceding) AS x
FROM ApplicationLog
) AS t
WHERE x = 1
GROUP BY App_name