Gaps and Islands 根据列序查询/重置行数
Gaps and Islands query / reset row count based on column seqeunce
我知道有很多这样的例子,但仍然找不到确切的解决方案。
我希望根据 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)
在上面的 table 中,我想要一个以 1 递增的行号列,按类别分区,但每次 window 更改时都需要重置计数。
到目前为止我最好的是:
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:
是这样的吗?
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
我知道有很多这样的例子,但仍然找不到确切的解决方案。
我希望根据 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)
在上面的 table 中,我想要一个以 1 递增的行号列,按类别分区,但每次 window 更改时都需要重置计数。
到目前为止我最好的是:
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:
是这样的吗?
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