我想计算连续几天(行),这很容易(给出类似问题的所有答案)。但是在我的数据集中,我有一组连续的行,日期如下:
1. 30/12/2010
2. 31/12/2010
3. 01/01/2011
4. 02/01/2011
看起来像一组(连续4天),但我想将这个组分成两组。所以当有:
1. 30/12/2010
2. 31/12/2010
3. 01/01/2011
4. 02/01/2011
5. 05/01/2011
6. 06/02/2011
7. 07/02/2011
我希望将其分为四组(而不是三组):
1. 30/12/2010
2. 31/12/2010
3. 01/01/2011
4. 02/01/2011
5. 05/01/2011
6. 06/02/2011
7. 07/02/2011
我正在使用SQL Server 2014
答案 0 :(得分:1)
您可以像这样对行进行编号:
DECLARE @T TABLE(id INT, dt DATE);
INSERT INTO @T VALUES
(1, '2010-12-30'),
(2, '2010-12-31'),
(3, '2011-01-01'),
(4, '2011-01-02'),
(5, '2011-01-05'),
(6, '2011-02-06'),
(7, '2011-02-07');
WITH CTE1 AS (
SELECT *, YEAR(dt) AS temp_year, ROW_NUMBER() OVER (ORDER BY dt) AS temp_rownum
FROM @T
), CTE2 AS (
SELECT CTE1.*, DATEDIFF(DAY, temp_rownum, dt) AS temp_dategroup
FROM CTE1
)
SELECT *, RANK() OVER (ORDER BY temp_year, temp_dategroup) AS final_rank
FROM CTE2
ORDER BY final_rank, dt
结果:
id dt temp_year temp_rownum temp_dategroup final_rank
1 2010-12-30 2010 1 40539 1
2 2010-12-31 2010 2 40539 1
3 2011-01-01 2011 3 40539 3
4 2011-01-02 2011 4 40539 3
5 2011-01-05 2011 5 40541 5
6 2011-02-06 2011 6 40572 6
7 2011-02-07 2011 7 40572 6
可以使用简化查询,但我选择显示所有列,以便更容易理解。 DATEDIFF
技巧被复制from this answer。