【问题标题】:Cross Join Query with Dates带日期的交叉连接查询
【发布时间】:2019-03-03 05:06:18
【问题描述】:

我有下表结果。

A 列 B 列

abc            a
xyz            b
pqr            c

现在有了特定的日期范围,即 2018-09-01 到 2018-09-10,我想与这些日期交叉连接,结果如下。如何做到这一点?

**Date**          **Column A**   **Column B**

2018-09-01         abc            a
2018-09-01         xyz            b
2018-09-01         pqr            c
2018-09-02         abc            a
2018-09-02         xyz            b
2018-09-02         pqr            c
2018-09-03         abc            a
2018-09-03         xyz            b
2018-09-03         pqr            c
.
.
.
2018-09-010        abc            a
2018-09-010        xyz            b
2018-09-010        pqr            c

【问题讨论】:

  • 请标记您的 DBMS。另外,这是日期表还是需要生成?
  • select * from table1 cross join datestable。 (其中 datetable 可以是基表或 cte。)

标签: sql cross-join


【解决方案1】:

尝试如下

 declare @sdate date = '2018-09-01'
    , @edate date = '2018-09-10'

; with dates_CTE (date) as (
        select @sdate 
    Union ALL
        select DATEADD(day, 1, date)
        from dates_CTE
        where date < @edate
) ,
t2 as
(
select 'abc' as col1, 'a' as  col2 
union all
select 'xyz','b'
union all
select 'pqr','c'       

) select * from t2 cross join dates_CTE


col1    col2    date
abc     a   01/09/2018 00:00:00
xyz     b   01/09/2018 00:00:00
pqr     c   01/09/2018 00:00:00
abc     a   02/09/2018 00:00:00
xyz     b   02/09/2018 00:00:00
pqr     c   02/09/2018 00:00:00
abc     a   03/09/2018 00:00:00
xyz     b   03/09/2018 00:00:00
pqr     c   03/09/2018 00:00:00
abc     a   04/09/2018 00:00:00
xyz     b   04/09/2018 00:00:00
pqr     c   04/09/2018 00:00:00
abc     a   05/09/2018 00:00:00
xyz     b   05/09/2018 00:00:00
pqr     c   05/09/2018 00:00:00
abc     a   06/09/2018 00:00:00
xyz     b   06/09/2018 00:00:00
pqr     c   06/09/2018 00:00:00
abc     a   07/09/2018 00:00:00
xyz     b   07/09/2018 00:00:00
pqr     c   07/09/2018 00:00:00
abc     a   08/09/2018 00:00:00
xyz     b   08/09/2018 00:00:00
pqr     c   08/09/2018 00:00:00
abc     a   09/09/2018 00:00:00
xyz     b   09/09/2018 00:00:00
pqr     c   09/09/2018 00:00:00
abc     a   10/09/2018 00:00:00
xyz     b   10/09/2018 00:00:00
pqr     c   10/09/2018 00:00:00

【讨论】:

    【解决方案2】:

    您需要生成日期。大多数数据库都支持这样的语法:

    select dates.dte, t1.a, t1.b
    from (select cast('2018-09-01' as date) as dte union all
          select cast('2018-09-02' as date) as dte union all
          . . .
          select cast('2018-09-10' as date) as dte
         ) dates cross join
         table1 t1
    order by date, a, b;
    

    如果您有日历表,请改用它。

    此外,某些数据库可能需要在子查询中使用 from dualfrom sysibm.sysdummy1。或者他们可能有其他方法来生成日期序列。

    【讨论】:

      猜你喜欢
      • 2012-12-31
      • 2016-06-14
      • 1970-01-01
      • 1970-01-01
      • 2013-04-04
      • 1970-01-01
      • 1970-01-01
      • 2015-08-02
      • 1970-01-01
      相关资源
      最近更新 更多