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

Sequentially number groups of values (including repeats)

我有以下 table:

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

我尝试了 window 函数的不同组合,但均未成功。目标是汇总数据,使其看起来像这样:

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

这是一个 gaps-and-island 问题,您希望将“相邻行”组合在一起。获得您正在寻找的最终结果的最简单方法可能是使用行号之间的差异来识别组:

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