【问题标题】:Select Date if between any row's start and end date如果在任何行的开始日期和结束日期之间,请选择日期
【发布时间】:2018-12-28 02:14:56
【问题描述】:

我正在使用此处显示的方法创建月份列表:Months between two dates

一旦我有了这些日期,我只想保留它们在特定客户的任何行的开始日期和结束日期之间的日期。

所以表格是:

client  start_date  end_date
1       2014-06-01  2016-02-29
1       2016-03-01  2016-12-31
1       2017-04-01  NULL

其中 NULL 表示在没有设置未来 end_date 的情况下仍处于活动状态。

所以我想要得到的是(我每个月都使用 EOMONTH):

2014-06-30
2014-07-31
... ect ...
2016-11-30
2016-12-31
2017-04-30
2017-05-31
... ect ...

因此,2016 年 12 月至 2017 年 4 月之间的月份不存在。每个客户端可以有任意数量的行。它们可能没有间隙,也可能有间隙,如上例所示。

【问题讨论】:

    标签: sql-server-2012


    【解决方案1】:

    所以我现在觉得有点傻!很简单:

    WITH dates AS (
    SELECT  EOMONTH(DATEADD(MONTH, x.number, '2016-01-01')) calendar_month
    FROM    master.dbo.spt_values x
    WHERE   x.type = 'P'        
        AND x.number <= DATEDIFF(MONTH, '2016-01-01', '2018-12-31'))
    
    SELECT
        dates.calendar_month
    
    FROM
        clients
        LEFT JOIN dates ON dates.calendar_month BETWEEN EOMONTH(clients.start_date) AND EOMONTH(clients.end_date) OR 
            (dates.calendar_month >= clients.start_date AND clients.end_date is NULL)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-31
      • 2017-11-02
      • 2021-08-05
      • 1970-01-01
      相关资源
      最近更新 更多