2017-04-26 36 views
0

您好,我遇到以下情况的问题。 我有一个表“应用程序日志”作为一列中具有相同值的多行

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”必然失败的一个应用程序名称的状态并返回作为结果。例如,如果n = 5,我的查询必须返回app_name = Application 3.

+0

你的问题不够清楚 – Mehr

+0

应用程序3在{0,1,2,3,4}中是否也失败了'n'? –

+0

对于{0,1,2,3,4}中的n也是失败的? – MileP

回答

2

以下查询在SQL Server中起作用。我看不出有任何理由为什么它不应该在甲骨文工作,以及:

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 

Demo here

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 
相关问题