2016-11-14 67 views
0

我正在嘗試解決我遇到的問題。計數日SQL Server

| ID | Op | Object | STATE | Timestamp | 
    | 01 | 1 | A  | 1 | 01-02-2016| 
    | 02 | 1 | A  | 2 | 04-02-2016| 
    | 03 | 1 | A  | 1 | 10-02-2016| 
    | 04 | 1 | A  | 3 | 01-02-2016| 
    | 05 | 2 | A  | 2 | 02-02-2016| 
    | 06 | 3 | A  | 1 | 05-02-2016| 
    | 07 | 3 | A  | 2 | 10-11-2016| 

我需要編寫返回計數的天,一個對象過去在狀態2 實施例中,對象A,從04-02到留在10-02 STATE 2 + 02-02一個SQL到05-02和從10-11到今天這麼6天+3天+4天。

SQL return 13 

目前通過代碼,但我需要它在SQL提取,我不知道如何繼續。這是可能的SQL?

謝謝

+0

我不明白這張桌子。在01-02-2016對象A切換到狀態1(記錄01)和狀態3(記錄04)?從2016年2月2日到2016年2月3日,它的狀態爲1(記錄01)和狀態2(記錄05)。 2016年4月2日,它有兩次狀態2(來自記錄05和02),05-02-2016有狀態2(來自記錄02)和狀態1(來自記錄06)。所以一個對象有多個狀態,你只能通過ID排序和查找重疊的日期範圍來確定哪個狀態和多少個狀態? –

回答

1

我想你想lead()採用聚集和日期邏輯一起:

select object, 
     sum(case when state = 2 then datediff(day, timestamp, coalesce(next_timestamp, getdate())) 
       else 0 
      end) as days_state_2 
from (select t.*, 
      lead(timestamp) over (partition by object order by timestamp) as next_timestamp 
     from t 
    ) t 
group by object; 

或者,您可以將過濾條件外select

select object, 
     sum(datediff(day, timestamp, coalesce(next_timestamp, getdate()))) as days_state_2 
from (select t.*, 
      lead(timestamp) over (partition by object order by timestamp) as next_timestamp 
     from t 
    ) t 
where state = 2 
group by object; 
+1

謝謝,不知道鉛(),它工作正常。 – BerithBE

1
select object, 
     sum(datediff(day, timestamp, coalesce(next_timestamp, getdate()))) as days_state_2 
from (select *, 
      lead(timestamp) over (partition by object order by timestamp) as next_timestamp 
     from #b 
    ) t 
where state = 2 
group by object; 
+0

謝謝,不知道鉛(),它工作正常。 – BerithBE