SQL Merge 3 tables by date where some dates are missing

扶醉桌前 提交于 2019-12-08 06:45:37

问题


I have 3 tables that I want to merge, each with a different column of interest. I also have an id variable that I want to do separate merges "within" id. The idea is that I want to merge X, Y, and Z by date (within ID), and have missing values if that date does not exist for a particular variable.

Table X:
ID     Date         X
1      2012-01-01   101
1      2012-01-02   102
1      2012-01-03   103
1      2012-01-04   104
1      2012-01-05   105
2      2012-01-01   150

Table Y:
ID     Date         Y
1      2012-01-01   301
1      2012-01-02   302
1      2012-01-03   303
1      2012-01-11   311
2      2012-01-01   350

Table Z:
ID     Date         Z
1      2012-01-01   401
1      2012-01-03   403
1      2012-01-04   404
1      2012-01-11   411
1      2012-01-21   421
2      2012-01-01   450

Desired Result Table:
ID     Date         X     Y     Z
1      2012-01-01   101   301   401
1      2012-01-02   102   302   .
1      2012-01-03   103   303   403
1      2012-01-04   104   .     404
1      2012-01-05   105   .     .
1      2012-01-11   .     311   411
1      2012-01-21   .     .     421
2      2012-01-01   150   350   450

Any ideas how to write this SQL statement? I've tried messing around with "full joins" and where statements for cross products, but I keep getting duplicate values for some of my ID-date combinations, or sometimes no ID.

Any help would be appreciated.


回答1:


Joins can be tricky things. My usual approach is to form the set of Keys first, and then use those keys to get what I want.

SELECT source.ID, source.Date, x.X, y.Y, z.Z
FROM
(
  SELECT ID, Date
  FROM TableX
  UNION
  SELECT ID, Date
  FROM TableY
  UNION
  SELECT ID, Date
  FROM TableZ
) as source
LEFT JOIN TableX x ON source.ID = x.ID AND source.Date = x.Date
LEFT JOIN TableY y ON source.ID = y.ID AND source.Date = y.Date
LEFT JOIN TableZ z ON source.ID = z.ID AND source.Date = z.Date
ORDER BY source.ID, source.Date


来源:https://stackoverflow.com/questions/9233372/sql-merge-3-tables-by-date-where-some-dates-are-missing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!