2015-05-20 26 views
1

連接SQL表我有如下表,表1十字按日期

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

而且有一個表2

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 

一個結果我試着用cross apply

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 

什麼是錯在我的代碼?

回答

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中有重疊的日期,它會變得雜亂。這可能不是你想要的,但如果你wa nted總結每個日期落入你會做這樣的事情的範圍內的所有值:

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 

否則,你會得到你的輸出重複的日期。

1

你並不需要一個交叉連接,但左連接:

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

運行代碼後,我得到了相同的結果我的。我想擁有table1中的所有日期(tally表包含所有365/366天),但是更改後的值取決於table2中的值。 – mko

1

一個LEFT JOIN將在這裏做的:

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

此代碼不會返回值爲0的表2中未提及的日期 – mko

+0

@mko:您是對的。而不是'table2.value',使用'COALESCE(table2.value,table1.value)'。 – davidhigh

1

試試這個查詢。我已將列名稱日期更改爲mydate.I猜測date是一個關鍵字。

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

+0

我用coalesce(table2.value,0) – mko