SQL计算状态连续出现的次数

时间:2016-11-07 10:32:39

标签: sql sql-server sql-server-2008-r2

我有一个包含案例列表的表格,以及他们拥有的状态列表:

Case ID | Date       | Status
------  | ---------- |-------
   x    | 2016-11-01 | Open
   x    | 2016-11-03 | Hold
   x    | 2016-11-04 | Hold
   x    | 2016-11-05 | Open
   x    | 2016-11-08 | Hold
   x    | 2016-11-15 | Processing
   x    | 2016-11-16 | Done

我想表明有一个新记录,但同一案件的状态保持不变:

Case ID | Date       | Status     | count
------  | ---------- |----------  |------
   x    | 2016-11-01 | Open       |  1 
   x    | 2016-11-03 | Hold       |  1
   x    | 2016-11-04 | Hold       |  2
   x    | 2016-11-05 | Open       |  1
   x    | 2016-11-08 | Hold       |  1
   x    | 2016-11-15 | Processing |  1
   x    | 2016-11-16 | Done       |  1

如果我这样做:

SELECT * 
FROM
    (SELECT 
         ROW_NUMBER() OVER  (partition by [Case ID], [status] ORDER BY Date) AS Row, 
         ID, Status, Date 
     FROM 
         Cases) AS C
WHERE 
    ID = x
ORDER BY
    Date

它没有考虑到最后一次'保持'是在'开放'之后并且排在第3位,但我需要数字1。

2 个答案:

答案 0 :(得分:2)

您需要检测具有相同status值的连续记录的岛屿并使用“岛屿ID”#39;在PARTITION BY窗口函数的ROW_NUMBER子句中:

SELECT  [Case ID], [Date], [status],
        ROW_NUMBER() OVER (PARTITION BY [Case ID], [status], grp ORDER BY [Date]) AS [count]
FROM (
   SELECT  [Case ID], [Date], [status], 
           ROW_NUMBER() OVER (PARTITION BY [Case ID] ORDER BY [Date]) -
           ROW_NUMBER() OVER (PARTITION BY [Case ID], [status] ORDER BY [Date]) AS grp   
   FROM Cases) AS t
ORDER BY [Date]

答案 1 :(得分:0)

您也可以在下面尝试..

SELECT  CASEID,
       DATE,
       STATUS,
     CASE WHEN RNO<>0 THEN  (rno+r) ELSE 1 END
            FROM
        (
SELECT CASEID,
       DATE,
       STATUS,
       CASE
         WHEN STATUS = LAG(STATUS)
                         OVER (
                           PARTITION BY CASEID
                           ORDER BY CASEID,date) THEN 1
         ELSE 0
       END RNO,
       ROW_NUMBER() OVER( partition by date,status ORDER BY DATE,status) R
FROM   #TABLE1 )A