2016-04-20 83 views
1

我知道有很多這樣的例子,但仍然無法找到確切的解決方案。基於列序列的差距和島嶼查詢/重置行計數

我正在尋找重置基於序列1和0的行數。

DECLARE @TestTable TABLE (category INT, ts INT,window int) 
INSERT INTO @TestTable (category,ts,window) 
VALUES (1,1,1),(1,2,1),(1,3,0),(1,4,0),(1,5,1),(1,6,1),(1,7,1),(2,1,0),(2,2,1),(2,3,1),(2,4,1),(2,5,0),(2,6,0),(2,7,1),(2,8,1),(2,9,1),(2,10,1),(2,11,1) 

enter image description here

在上面的表中,我想的行數列由1遞增,按類別劃分,但是計數需要每次重置窗口的變化。

最好我到目前爲止得到的是:

SELECT 
    x.category, 
    ts, 
    window, 
    is_group, 
    SUM(is_group) OVER (PARTITION BY x.category ORDER BY ts ROWS BETWEEN 1 PRECEDING AND 0 FOLLOWING) * is_group 
FROM 
    (
    SELECT 
     *, 
     CASE WHEN LAG(window) OVER(PARTITION BY category ORDER BY ts ) = window THEN 1 ELSE 0 END is_group 
    FROM @TestTable 
    ) x 
ORDER BY x.category,ts 

作品,但最後一段也不會增加行數進一步比2:

enter image description here

回答

2

是這樣的嗎?

DECLARE @TestTable TABLE (category INT, ts INT,window int) 
INSERT INTO @TestTable (category,ts,window) 
VALUES (1,1,1),(1,2,1),(1,3,0),(1,4,0),(1,5,1),(1,6,1),(1,7,1),(2,1,0),(2,2,1),(2,3,1),(2,4,1),(2,5,0),(2,6,0),(2,7,1),(2,8,1),(2,9,1),(2,10,1),(2,11,1); 


with ctex 
as 
(
SELECT 
x.category, 
ts, 
window, 
is_group, 
sum(is_group) over (partition by category order by ts) as groupstot 


FROM 
(
SELECT 
    *, 
    CASE WHEN LAG(window) OVER(PARTITION BY category ORDER BY ts ) = window THEN 0 ELSE 1 END is_group 
FROM @TestTable 
) x 

) 
Select * , row_number() over(partition by category,groupstot order by ts) from ctex 
ORDER BY category,ts 
+0

完美,這是做到了。謝謝 –