SQL Full Outer Join

时间:2012-11-19 04:12:30

标签: sql join

我正在尝试编写一个join语句来将以下三个数据集连接在一起。 (这是使用MS SQL Server)

Set 1
ID    Date    Col1 
1     Jan 11  a1 
1     Jan 13  a2

Set 2
ID    Date    Col2 
1     Jan 11  b1 
1     Jan 15  b2

Set 3
ID    Date    Col3
1     Jan 15  c1 
1     Jan 17  c2

Combined Set
ID    Date    Col1    Col2    Col3
1     Jan 11  a1      b1
1     Jan 13  a2
1     Jan 15          b2       c1
1     Jan 17                   c2       

我认为完全外部联接能够做到这一点,但我遇到了主要的跨产品问题。

3 个答案:

答案 0 :(得分:3)

尝试一下:

select coalesce(t1.date, t2.date, t3.date) date, col1, col2, col3 from table1 t1
full outer join table2 t2 on (t1.date = t2.date)
full outer join table3 t3 on (t2.date = t3.date)

答案 1 :(得分:1)

根据您的数据集,您似乎想要根据date列加入3个表格。请注意,我在此忽略了ID列,直到您澄清为什么所有ID都设置为1。

SELECT ISNULL(set1.dt, ISNULL(set2.dt, set3.dt)) as 'Date', col1, col2, col3
FROM set1
FULL OUTER JOIN set2 ON CAST(set1.dt AS DATE) = CAST(set2.dt AS DATE)
FULL OUTER JOIN set3 ON CAST(set2.dt AS DATE) = CAST(set3.dt AS DATE)

答案 2 :(得分:1)

SELECT ISNULL(a.ID,isnull(b.ID,c.ID)) ID,coalesce(a.dt, b.dt, c.dt) , Col1, Col2, Col3 FROM set1 a FULL OUTER JOIN set2 b ON a.dt = b.dt FULL OUTER JOIN set3 c ON b.dt= c.dt