合并两个表中的数据来计算联系人数量,尝试使用联合

发布于 2024-12-22 10:29:52 字数 607 浏览 0 评论 0原文

我有两张桌子。一个跟踪零件发货,另一个跟踪系统发货。 我试图计算每个表中的客户联系人,结果显示零件和系统的客户联系人总数。 我正在尝试使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

鸠魁 2024-12-29 10:29:52

你不能那样做。 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.

超可爱的懒熊 2024-12-29 10:29:52

UNION 需要创建派生表(从查询创建的表)。

SELECT * 
FROM (
    SELECT col1, col2
    FROM table
) UNION (
    SELECT col1, col2
    FROM otherTable
)

我也不认为你可以在组成 UNION 的选择中使用 GROUP BY (我已经有一段时间没有使用它了,所以我不太记得了)

UNION requires the creation of derived tables (tables created from a query).

SELECT * 
FROM (
    SELECT col1, col2
    FROM table
) UNION (
    SELECT col1, col2
    FROM otherTable
)

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)

楠木可依 2024-12-29 10:29:52

您是否尝试过在 UNION 查询结果中使用 GROUP BYSUM

Do you have tried to use a GROUP BY and SUM from the results of UNION query?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文