简体   繁体   English

SQL Full Outer Join

[英]SQL Full Outer Join

I am trying to write a join statement to join the following three data sets together. 我正在尝试编写一个join语句来将以下三个数据集连接在一起。 (This is using MS SQL Server) (这是使用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

I think a full outer join is able to do this but I am running into major cross product issues. 我认为完全外部联接能够做到这一点,但我遇到了主要的跨产品问题。

Give this a try: 尝试一下:

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)

Based on your dataset, you seem like you want to join the 3 tables based on the date column. 根据您的数据集,您似乎想要根据date列加入3个表。 Note that I'm disregarding the ID column here, until you clarify why all the IDs are set to 1. 请注意,我在此忽略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)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM