基于列序列的间隙和孤岛查询/重置行数
Posted
技术标签:
【中文标题】基于列序列的间隙和孤岛查询/重置行数【英文标题】:Gaps and Islands query / reset row count based on column seqeunce 【发布时间】:2016-04-20 09:00:52 【问题描述】:我知道有很多这样的例子,但仍然找不到确切的解决方案。
我希望根据 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)
在上表中,我想要一个递增 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:
【问题讨论】:
【参考方案1】:这样的?
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
【讨论】:
完美,做到了。谢谢以上是关于基于列序列的间隙和孤岛查询/重置行数的主要内容,如果未能解决你的问题,请参考以下文章