SQL按日期合并3个表,其中某些日期丢失
我有 3 个要合并的表,每个表都有不同的感兴趣列。我还有一个 id 变量,我想在“id”内进行单独的合并。我的想法是,我想按日期(ID 内)合并 X、Y 和 Z,并且如果特定变量不存在该日期,则缺少值。
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
有什么想法如何编写这个 SQL 语句吗?我尝试过使用“完全连接”和交叉产品的 where 语句,但我不断收到某些 ID-日期组合的重复值,或者有时没有 ID。
任何帮助将不胜感激。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(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.