gpt4 book ai didi

sql - SQL Server 2012 中的编号岛

转载 作者:行者123 更新时间:2023-12-04 23:18:58 26 4
gpt4 key购买 nike

我需要对 SQL Server 2012 中的岛进行编号。岛被定义为一组行,其中 DateFrom 之间没有天间隔。和 DateTo同内ItemId )。

以下数据集:

CREATE TABLE #Ranges (ItemId INT, DateFrom DATETIME, DateTo DATETIME)

INSERT INTO #Ranges VALUES (1,'2015-01-31','2015-02-17')
INSERT INTO #Ranges VALUES (1,'2015-02-18','2015-03-31')
INSERT INTO #Ranges VALUES (1,'2015-04-14','2015-05-21')
INSERT INTO #Ranges VALUES (2,'2015-07-12','2015-07-19')
INSERT INTO #Ranges VALUES (2,'2015-07-20','2015-07-24')
INSERT INTO #Ranges VALUES (2,'2015-07-26','2015-08-02')
INSERT INTO #Ranges VALUES (2,'2015-08-03','2015-08-07')

应编号如下:
ItemId;  DateFrom;    DateTo;      Number
1; 2015-01-31; 2015-02-17; 1
1; 2015-02-18; 2015-03-31; 1
1; 2015-04-14; 2015-05-21; 2
2; 2015-07-12; 2015-07-19; 3
2; 2015-07-20; 2015-07-24; 3
2; 2015-07-26; 2015-08-02; 4
2; 2015-08-03; 2015-08-07; 4

非常感谢任何帮助。

问候,
普热梅克

最佳答案

如果你只想给它们编号,那么我建议lag()累积总和:

select t.*,
sum(case when datefrom = dateadd(day, 1, prev_dateto
then 0 else 1
end) over (order by itemId, datefrom)
from (select t.*,
lag(dateto) over (partition by itemid order by datefrom) as prev_dateto
from table t
) t;
case确定新岛屿的起点。累积总和只是对这个标志求和。

关于sql - SQL Server 2012 中的编号岛,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32808583/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com