按日期交叉连接sql表

时间:2015-05-20 22:32:23

标签: sql sql-server sql-server-2008 tsql cross-join

我有一张下表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

我的代码有什么问题?

4 个答案:

答案 0 :(得分:1)

您不需要交叉加入,但需要左连接:

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

答案 1 :(得分:1)

LEFT JOIN将在此处执行:

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

答案 2 :(得分:1)

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

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

如果你在表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

否则您将在输出中获得重复日期。

答案 3 :(得分:1)

尝试此查询。我已将列名日期更改为mydate。我猜日期是关键字。

  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;

这是小提琴: http://sqlfiddle.com/#!9/85265/1