SQL:用总和连接 3 个表,过滤非聚合列
我有以下表格:
Plant:
ID Name
1 Plant1
2 Plant2
......
Rejects:
PlantID Quantity Date
1 20 01/02/2012
1 3 02/02/2012
2 30 03/02/2012
.....
Parts
PlantID Quantity Date
1 300 01/02/2012
2 500 01/02/2012
1 600 02/02/2012
.......
我正在尝试将这三个表连接起来,以便在两个日期之间获得每个工厂的零件和拒绝的总和:
Plant Parts Rejects
Plant1 900 23
Plant2 500 30
.....
我尝试过连接,它只是将总和相乘,并且我尝试过子查询,但会成功不允许我使用日期过滤器,因为它没有在 group by 子句中使用。
有人可以帮忙吗?
I have the following tables:
Plant:
ID Name
1 Plant1
2 Plant2
......
Rejects:
PlantID Quantity Date
1 20 01/02/2012
1 3 02/02/2012
2 30 03/02/2012
.....
Parts
PlantID Quantity Date
1 300 01/02/2012
2 500 01/02/2012
1 600 02/02/2012
.......
I'm trying to join the three so that I have a sum of parts and rejects per plant between two dates:
Plant Parts Rejects
Plant1 900 23
Plant2 500 30
.....
I've tried joins, which just multiplies the sums and I've tried subqueries that won't let me use a date filter because it's not used in the group by clause.
Can anyone help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这就能解决问题:
您可以使用
ID
在所有表之间进行INNER JOIN
。之后,您只需要Parts
和Rejects
中的Quantities
的SUM
即可。为此,您需要使用GROUP BY
。This will do the trick:
You make the
INNER JOIN
between all tables usingID
. Afterwards you just need theSUM
of theQuantities
inParts
andRejects
. For that you need to use theGROUP BY
.以下内容应该有效(使用预言机):
请注意,这不会使工厂没有废品或零件。
The following should work (using oracle):
Note that this will not get plants with no rejects or parts.