获得日期组中第一行,其中有一系列不间断的日期

问题描述 投票:2回答:1
DECLARE @TestData TABLE (
    Idntty    Int    Not Null
    ,[DATE] DATE NOT NULL
    ,[TYPE] VARCHAR(20) NOT NULL
    )
INSERT INTO @TestData VALUES 
(1,  '2016-03-01', 'Inventory'),
(2,  '2016-03-01', 'Inventory'), 
(3,  '2016-04-01', 'Inventory'), 
(4,  '2016-04-01', 'Inventory'), 
(5,  '2016-06-01', 'Inventory'), 
(6,  '2016-06-01', 'Inventory'), 
(7,  '2016-07-01', 'Inventory'), 
(8,  '2016-07-01', 'Inventory'), 
(9,  '2016-08-01', 'Inventory'), 
(10, '2016-08-01', 'Inventory'), 
(11, '2016-09-01', 'Inventory'), 
(12, '2016-09-01', 'Inventory')
;

基本上,我需要获得LAST组中的第一行,其中有一系列不间断的日期。

例如,此处'2016-03-01'可能不正确,因为缺少'2016-05-01',因此此日期记录的顺序有所中断。

所以我需要将'2016-06-01'作为其连续序列的第一个日期记录的输出,直到'2016-09-01'

我曾尝试使用标准的“孤岛”解决方案,但未取得任何成功,例如在此处按组申请。

我只想使用SQL解决问题。

sql sql-server tsql date gaps-and-islands
1个回答
2
投票

这确实是一个空白与孤岛的问题。基本上你想他最后一个岛的开始。这是使用窗口函数的一个选项:

select max(date) res
from (
    select t.*, lag(date) over(partition by type order by Idntty) lag_date
    from mytable t
) t
where lag_date is null or date > dateadd(day, 1, lag_date)

[在子查询中,lag()为您提供“上一个”记录的日期。然后,外部查询将筛选日期与上一条记录(即每个岛的开始)相差大于1天的行,并在此结果集中获取最大日期。

© www.soinside.com 2019 - 2024. All rights reserved.