date/calendar table 连续交易假期的最大数量

Maximum number of consecutive trading holidays from a date/calendar table

我正在尝试从交易 date/calendar table 中找出连续交易假期的最大数量。我在 TradingDate table 中有一个标志 isTradingHoliday = 1 表示交易假期的日期,否则 isTradingHoliday = 0。如何知道哪个日期区间是那个TradingDatetable连续交易假期最多的?

这听起来像是一个缺口和孤岛问题。您可以使用行号的差异找到第一个日期和天数。剩下的就是聚合和过滤了:

select top (1) with ties min(tradingdate) as startdate,
       max(tradingdate) as enddate
from (select c.*,
             row_number() over (order by tradingdate) as seqnum,
             row_number() over (partition by isTradingHoliday order by tradingdate) as seqnum_h
      from calendar c
     ) c
where isTradingHoliday = 1
group by isTradingHoliday, (seqnum - seqnum_h)
order by count(*) desc