每个州每个项目的天数,该期间的全部价值

时间:2016-06-03 17:59:55

标签: sql sql-server-2012

这篇文章与我的问题非常相似: SQL Server : how many days each item was in each state

但是我没有列修订来查看以前的状态,而且我想获得状态的全部时间,我b

...

我想知道一件物品一般处于一种状态多长时间,我的表格如下:

    ID                                      DATE                     STATUS
    3D56B7B1-FCB3-4897-BAEB-004796E0DC8D    2016-04-05 11:30:00.000  1
    3D56B7B1-FCB3-4897-BAEB-004796E0DC8D    2016-04-08 11:30:00.000  13
    274C5DA9-9C38-4A54-A697-009933BB7B7F    2016-04-29 08:00:00.000  5
    274C5DA9-9C38-4A54-A697-009933BB7B7F    2016-05-04 08:00:00.000  4
    A70A66DC-9D9E-49BE-93CF-00F9E3E06CE2    2016-04-14 07:50:00.000  1
    A70A66DC-9D9E-49BE-93CF-00F9E3E06CE2    2016-04-21 14:00:00.000  2
    A70A66DC-9D9E-49BE-93CF-00F9E3E06CE2    2016-04-23 12:15:00.000  3
    A70A66DC-9D9E-49BE-93CF-00F9E3E06CE2    2016-04-23 16:15:00.000  1
    BF122AE1-CB39-4967-8F37-012DC55E92A7    2016-04-05 10:30:00.000  1
    BF122AE1-CB39-4967-8F37-012DC55E92A7    2016-04-20 17:00:00.000  5

我想得到这个

Column 1 : ID Column 2 : Status Column 3 : Time with the status
  

第3列:状态的时间    = NextDate - PreviosDate + 1

  • 如果是最后一个状态,则计为1
  • 如果在同一天有多个状态,我会收到最后一个(你可以说这只是当天的最后一个状态)
  • 按ID,状态必须是唯一的

我应该是这样的:

ID                                      STATUS      TIME
3D56B7B1-FCB3-4897-BAEB-004796E0DC8D    1           3
3D56B7B1-FCB3-4897-BAEB-004796E0DC8D    13          1
274C5DA9-9C38-4A54-A697-009933BB7B7F    5           5
274C5DA9-9C38-4A54-A697-009933BB7B7F    4           1
A70A66DC-9D9E-49BE-93CF-00F9E3E06CE2    1           8
A70A66DC-9D9E-49BE-93CF-00F9E3E06CE2    2           2   
BF122AE1-CB39-4967-8F37-012DC55E92A7    1           15
BF122AE1-CB39-4967-8F37-012DC55E92A     5           1

1 个答案:

答案 0 :(得分:1)

感谢@ConradFrix评论,这是有效的方法..

WITH CTE
    AS
    (
        SELECT
        ID,
        STATUS, 
        DATE, 
        LEAD(DATE, 1) over (partition by ID order by DATE) LEAD,
        ISNULL(DATEDIFF(DAYOFYEAR,  DATE,
        LEAD(DATE, 1) over (partition by ID order by DATE)), 1)  DIF_BY_LEAD
        FROM TABLE_NAME
    )
    SELECT ID, STATUS, SUM(DIF_BY_LEAD) AS TIME_STATUS 
    FROM CTE GROUP BY ID, STATUS
    ORDER BY ID, STATUS