连续编号的值组(包括重复)

Posted

技术标签:

【中文标题】连续编号的值组(包括重复)【英文标题】:Sequentially number groups of values (including repeats) 【发布时间】:2020-09-22 14:31:23 【问题描述】:

我有下表:

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】:

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

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

编号 |类别 |日期从 |日期到 -: | :------- | :--------- | :--------- 1 | AAA | 2020-06-25 | 2020-06-25 1 |血脑屏障 | 2020-06-26 | 2020-06-27 1 | AAA | 2020-06-28 | 2020-06-29 1 |血脑屏障 | 2020-06-30 | 2020-06-30 1 | AAA | 2020-07-01 | 2020-07-01 2 | AAA | 2020-06-25 | 2020-06-25 2 |血脑屏障 | 2020-06-26 | 2020-06-27 2 | AAA | 2020-06-28 | 2020-06-29 2 |血脑屏障 | 2020-06-30 | 2020-06-30 2 | AAA | 2020-07-01 | 2020-07-01

【讨论】:

以上是关于连续编号的值组(包括重复)的主要内容,如果未能解决你的问题,请参考以下文章

映射常量值组[重复]

mysql的concat值组[重复]

Dynamics 365中定制包括一个流水号但不会产生重复编号的功能

使用 Python 将索引设置为 csv 文件中的重复行值组

oracle 查询不连续的值?

sql server存储过程产生连续不重复编号