我有两个桌子。第一个表TBL1只有一列,其中包括日期:
[date]
2017-10-03
2017-10-04
2017-10-05
2017-10-06
....
第二张表TBL2:
Date Code Index Domain
2017-10-03 1 542 xxx.com
2017-10-03 680 652 xxx.com
2017-10-06 1 235 xxx.com
2017-10-06 680 125 xxx.com
我想要一个这样的结构:
Date Code Index Domain
2017-10-03 1 542 xxx.com
2017-10-03 680 652 xxx.com
2017-10-04 1 NULL xxx.com
2017-10-04 680 NULL xxx.com
2017-10-05 1 NULL xxx.com
2017-10-05 680 NULL xxx.com
2017-10-06 1 235 xxx.com
2017-10-06 680 125 xxx.com
如何在SQL中生成类似的内容?
答案 0 :(得分:2)
使用cross join
生成行,使用left join
引入列:
select t1.date, cd.code, t2.index, cd.domain
from tbl1 t1 cross join
(select distinct code, domain from tbl2) cd left join
tbl2 t2
on t2.date = t1.date and t2.code = cd.code and t2.domain = cd.domain;