按日期交叉连接 sql 个表

Cross joining sql tables by date

我有一个关注 table , table1

date            value   
-------------------------
2015-01-01      0
2015-01-02      0
2015-01-03      0
2015-01-04      0

还有一个table2

datestart       dateend         value   
-------------------------------------
2015-01-02      2015-01-03      1

我想得到如下结果

date            value   
-------------------------
2015-01-01      0
2015-01-02      1
2015-01-03      1
2015-01-04      0

我尝试使用交叉应用

select table1.date, temp.value
from table1
cross join
(select table2.value from table2 where
table2.startdate <= table1.date and table2.enddate > table1.date) as temp

但我最终得到了

date            value   
-------------------------
2015-01-02      1
2015-01-03      1

我的代码有什么问题?

您不需要交叉联接,但需要左联接:

SELECT    table1.date, table2.value
FROM      table1
LEFT JOIN table2 ON table1.date BETWEEN table2.startdate AND table2.enddate

A LEFT JOIN 将在此处执行:

SELECT table1.date, table2.value
FROM table1
LEFT JOIN
table2
ON table2.startdate <= table1.date
AND table2.enddate > table1.date

您可以像这样使用左连接:

select table1.date, coalesce(table2.value,0) Value
from table1
left join table2
on table1.date between table2.startdate and table2.enddate 
order by 1

虽然如果 table 中的日期重叠会变得混乱 2. 这可能不是您想要的,但是如果您想对每个日期所属范围的所有值求和,您会做这样的事情:

select table1.date, sum(coalesce(table2.value,0)) Value
from table1
left join table2
on table1.date between table2.startdate and table2.enddate 
group by table1.date

否则你会在输出中得到重复的日期。

试试这个查询。我已将列名称日期更改为 mydate.I 猜测日期是关键字。

  select t1.mydate, (case when t2.value is null then 0 else t2.value end) as value from table1 t1 left join table2 t2 
    on t1.mydate between t2.datestart and t2.dateend order by mydate;

这是 fiddle: http://sqlfiddle.com/#!9/85265/1