合并两个表中的数据来计算联系人数量,尝试使用联合
我有两张桌子。一个跟踪零件发货,另一个跟踪系统发货。 我试图计算每个表中的客户联系人,结果显示零件和系统的客户联系人总数。 我正在尝试使用 Union,从我的结果来看我猜我做错了。我的结果最终为客户提供了两个条目。 Cust A 总共有 9 个,然后另一个条目为 1。所以我猜没有合并客户联系人,它只是创建两个结果的并集。
我正在使用的代码。
SELECT Count(part_shipment.Customer_Station_ID) AS Contact,
part_shipment.Customer_Station_ID AS Customer
FROM part_shipment
GROUP BY part_shipment.Customer_Station_ID
UNION
SELECT Count(system_shipments.Customer_Station_ID) AS Contact,
system_shipments.Customer_Station_ID AS Customer
FROM system_shipments
GROUP BY system_shipments.Customer_Station_ID
ORDER BY Contact DESC
I have two tables. One tracks Part Shipments and the other tracks System shipments.
I am trying to count the customer contacts in each table with the result showing me the total customer contacts for both parts and systems combined.
I am trying to use Union and I would guess from my results I am doing this all wrong. My results end up with two entries for customers. Cust A will have a total of 9 and then another entry of 1. So I am guess there is no merge of the customer contacts and it is just creating a union of both results.
The Code I am using.
SELECT Count(part_shipment.Customer_Station_ID) AS Contact,
part_shipment.Customer_Station_ID AS Customer
FROM part_shipment
GROUP BY part_shipment.Customer_Station_ID
UNION
SELECT Count(system_shipments.Customer_Station_ID) AS Contact,
system_shipments.Customer_Station_ID AS Customer
FROM system_shipments
GROUP BY system_shipments.Customer_Station_ID
ORDER BY Contact DESC
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你不能那样做。 Union 只是从第一个查询中获取行,从第二个查询中获取行,然后一个接一个地“显示”它们。
You can't do it like that. The Union just take rows from first query and rows from second query, and "display" them ones after anothers.
UNION 需要创建派生表(从查询创建的表)。
我也不认为你可以在组成 UNION 的选择中使用 GROUP BY (我已经有一段时间没有使用它了,所以我不太记得了)
UNION requires the creation of derived tables (tables created from a query).
I also don't think you can use GROUP BY inside the selects that make up the UNION (it's been a while since I used it so I don't remember for sure)
您是否尝试过在
UNION
查询结果中使用GROUP BY
和SUM
?Do you have tried to use a
GROUP BY
andSUM
from the results ofUNION
query?