【问题标题】:SQL Cross Join getting all dates between date rangeSQL Cross Join 获取日期范围内的所有日期
【发布时间】:2018-05-11 11:08:15
【问题描述】:

我有一个结构如下的表:

ID:开始日期:结束日期

我想为每个 ID 显示日期范围内的所有日期。

例如

ID = 1: StartDate = 01/01/2018: EndDate = 03/01/2018
ID: 1 01/01/2018
ID: 1 02/01/2018
ID: 1 03/01/2018 

我想我需要使用交叉连接,但我不确定如何为多行创建它?

【问题讨论】:

  • 请告诉我们您使用的是哪个数据库,因为答案可能取决于此。
  • 用您正在使用的数据库标记您的问题。
  • 这可以在没有 CTE 的情况下仅使用交叉连接或交叉应用来完成吗?

标签: sql sql-server-2012


【解决方案1】:

这里是 SQL Server 的 CTE,语法有些不同:

declare @startdate date = '2018-01-01';
declare @enddate date = '2018-03-18';

with
  dates as (
    select @startdate as [date]
    union all
    select dateadd(dd, 1, [date]) from dates where [date] < @enddate
  )
select [date] from dates

【讨论】:

    【解决方案2】:

    所以我最终使用了一个日期表并只是交叉引用它

    select *
    from Date d
    inner join WorkingTable w
           on d.Date >= w.StartDate 
           and d.date < w.EndDate 
    

    【讨论】:

    【解决方案3】:

    在标准 SQL 中,您可以使用递归 CTE:

    with recursive dates as (
          select date '2018-01-01' as dte
          union all
          select dte + interval '1 day'
          from dates
          where dte < date '2018-01-03'
         )
    select dte
    from dates;
    

    确切的语法(是否需要recursive 和日期函数)因数据库而异。并非所有数据库都支持此标准功能。

    【讨论】:

      【解决方案4】:

      现在只用一个 id..,

      create table #dateTable(id int, col1 date, col2 date)
      
      insert into #dateTable values(1,'05-May-2018','08-May-2018') ,(2,'05-May-2018','05-May-2018') 
      
      select *from #dateTable
      
      with cte(start, ends) as(
      select  start = (select top 1 col1 from #dateTable), ends = (select top 1 col2 from #dateTable)
      union all
      select DATEADD(dd,1,start),ends from cte where start <> ends
      )select start from cte option (maxrecursion 10)
      

      我还在工作...我很快就会更新...!

      【讨论】:

        猜你喜欢
        • 2012-02-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-05
        • 1970-01-01
        • 1970-01-01
        • 2014-11-01
        • 1970-01-01
        相关资源
        最近更新 更多