2017-05-26 50 views
0

所以我有這樣的一個表:一個布爾條件計是具備條件的sql月

---id---datetime---month---active 
    1 2016-12-01 Dec-16 0 
    1 2016-12-02 Dec-16 1 
    1 2017-01-28 Jan-17 1 
    1 2017-02-03 Feb-17 0 
    1 2017-02-24 Feb-17 0 
    1 2017-03-05 Mar-17 0 
    1 2017-03-24 Mar-17 1 
    1 2017-04-02 Apr-17 1 
    1 2017-04-25 Apr-17 1 
    1 2017-05-02 May-17 1 
    1 2017-05-28 May-17 0 

我想這樣的結果:

---id---monthCount---Active 
    1  1   0 
    1  2   1 
    1  2   0 
    1  3   1 
    1  1   0 

表確實有更多的比1 id

現在我剛剛起步的最小和最大日之間的差異使用由idactive和排序由datetime分區和排名,但是這給了我當它第一次進入到1之間的幾個月,最後當它更改爲0.我希望它通過active的每次更改進行詳細分隔。

我該如何做到這一點?

回答

0

在SQL Server 2012+,你可以使用LAG這樣

DECLARE @SampleData AS TABLE 
(
    id int, 
    [datetime] datetime, 
    active bit 
) 


;WITH temp AS 
(
    SELECT sd.id, 
      sd.active, 
      sd.[datetime], 
      lag(sd.active) over(PARTITION BY sd.id ORDER BY sd.datetime) AS previousActive, 
      lag(sd.id) over(ORDER BY sd.id, sd.datetime) AS previousId 
    FROM @SampleData sd 
) 
,temp1 AS 
(
    SELECT *, 
      sum(CASE WHEN t.previousActive IS NULL OR t.previousActive != t.active OR t.id != t.previousId THEN 1 
      ELSE 0 END) 
      OVER(PARTITION BY t.id ORDER BY t.[datetime]) AS groupid 
    FROM temp t 
) 
SELECT t.id, count(DISTINCT month(t.datetime)) AS monthCount, t.active 
FROM temp1 t 
GROUP BY id, t.groupid, t.active 

演示鏈接:http://rextester.com/SJZ16279

0

您可以使用行號差異來識別組(這是一個間隙和孤島問題)。那麼最終的解決方案需要count(distinct)

select id, count(distinct month) as monthcount, active 
from (select t.*, 
      row_number() over (partition by id order by month, active) as seqnum_i, 
      row_number() over (partition by id, active order by month) as seqnum_ia 
     from t 
    ) t 
group by id, active, (seqnum_i - seqnum_ia); 

這是假設數據是由ID,月活躍有序的 - 這是問題的數據的排序。真的會更好的是有一個明確定義行排序順序的列。

+0

什麼是括號?當我嘗試運行代碼時出現錯誤,因爲語法不正確,我從來沒有看到可以解釋的分組。這是一個錯誤嗎? –