值的顺序编号组(包括重复)

时间:2020-09-22 14:31:23

标签: sql sql-server datetime window-functions gaps-and-islands

我有下表:

IF OBJECT_ID('tempdb..#Temp') IS NOT NULL
    DROP TABLE #Temp
CREATE TABLE #Temp
(
    ID INT,
    Category VARCHAR(100),
    [Date] DATE
)
INSERT INTO #Temp VALUES 
(1,'AAA','20200625'),
(1,'BBB','20200626'),
(1,'BBB','20200627'),
(1,'AAA','20200628'),
(1,'AAA','20200629'),
(1,'BBB','20200630'),
(1,'AAA','20200701'),
(2,'AAA','20200625'),
(2,'BBB','20200626'),
(2,'BBB','20200627'),
(2,'AAA','20200628'),
(2,'AAA','20200629'),
(2,'BBB','20200630'),
(2,'AAA','20200701')

我不知道如何为这样的类别分配顺序整数:

ID  Category    Date        GroupNumber
-------------------------------------------
1   AAA         25/06/2020  1
1   BBB         26/06/2020  2
1   BBB         27/06/2020  2
1   AAA         28/06/2020  3
1   AAA         29/06/2020  3
1   BBB         30/06/2020  4
1   AAA         01/07/2020  5
2   AAA         25/06/2020  1
2   BBB         26/06/2020  2
2   BBB         27/06/2020  2
2   AAA         28/06/2020  3
2   AAA         29/06/2020  3
2   BBB         30/06/2020  4
2   AAA         01/07/2020  5

我尝试了不同的窗口功能组合,但没有成功。目标是汇总数据,使其看起来像这样:

ID  Category    Date        DateFrom    DateTo
--------------------------------------------------
1   AAA         25/06/2020  25/06/2020  25/06/2020
1   BBB         26/06/2020  26/06/2020  27/06/2020
1   AAA         28/06/2020  28/06/2020  29/06/2020
1   BBB         30/06/2020  30/06/2020  30/06/2020
1   AAA         01/07/2020  01/07/2020  01/07/2020
2   AAA         25/06/2020  25/06/2020  25/06/2020
2   BBB         26/06/2020  26/06/2020  27/06/2020
2   AAA         28/06/2020  28/06/2020  29/06/2020
2   BBB         30/06/2020  30/06/2020  30/06/2020
2   AAA         01/07/2020  01/07/2020  01/07/2020

1 个答案:

答案 0 :(得分:2)

这是一个空白问题,您想将“相邻行”组合在一起。获得最终结果的最简单方法可能是使用行号之间的差异来识别组:

select id, category, min(date) datefrom, max(date) dateto
from (
    select t.*, 
        row_number() over(partition by id order by date) rn1,
        row_number() over(partition by id, category order by date) rn2
    from #temp t
) t
group by id, category, rn1 - rn2
order by id, datefrom

Demo on DB Fiddle

id | category | datefrom   | dateto    
-: | :------- | :--------- | :---------
 1 | AAA      | 2020-06-25 | 2020-06-25
 1 | BBB      | 2020-06-26 | 2020-06-27
 1 | AAA      | 2020-06-28 | 2020-06-29
 1 | BBB      | 2020-06-30 | 2020-06-30
 1 | AAA      | 2020-07-01 | 2020-07-01
 2 | AAA      | 2020-06-25 | 2020-06-25
 2 | BBB      | 2020-06-26 | 2020-06-27
 2 | AAA      | 2020-06-28 | 2020-06-29
 2 | BBB      | 2020-06-30 | 2020-06-30
 2 | AAA      | 2020-07-01 | 2020-07-01