2017-04-26 35 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 
相關問題