带日期的交叉联接查询

时间:2018-09-27 09:58:50

标签: sql cross-join

我有下表的结果。

列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

2 个答案:

答案 0 :(得分:0)

尝试如下

 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

答案 1 :(得分:0)

您需要生成日期。大多数数据库都支持以下语法:

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。或者他们可能还有其他方法来生成日期序列。