“将子查询合并表时,子查询返回的值大于1]”>

问题描述 投票:0回答:2

我从前两个查询中有两个表,试图将它们组合成一个表,以按州显示供应商总数和消费者总数。

我希望使用子查询来做到这一点,但是我无法弄清楚如何使用GROUP BY语句并且不会出现“子查询返回了多个值”错误。对于第三个查询的任何建议将不胜感激。

SELECT State, COUNT(Supp_ID) Suppliers
FROM Tb_Supplier
GROUP BY State;

SELECT State, COUNT(Con_ID) Consumers
FROM Tb_Consumer
GROUP BY State;

SELECT s.State, COUNT(s.Supp_ID) Suppliers, (SELECT COUNT(c.Con_ID)
                                             FROM Tb_Consumer c
                                             GROUP BY c.State) Consumers
FROM Tb_Supplier s
GROUP BY s.State

我从前两个查询中有两个表,试图将它们组合成一个表,以按州显示供应商总数和消费者总数。我希望使用子查询来完成它,...

sql-server
2个回答
0
投票
-- I think this is easier to manage, especially if you include more counts.
-- It will include suppliers from states without consumers and 
-- consumers living in states without suppliers.


SELECT State, SUM(Suppliers) Suppliers, SUM(Consumers) Consumers
FROM (
     SELECT State, COUNT(1) Suppliers, 0 Consumers
     FROM Tb_Supplier
     GROUP BY State

     UNION ALL

     SELECT State, 0 Suppliers, COUNT(1) Consumers
     FROM Tb_Consumer
     GROUP BY State) Report
GROUP BY State

1
投票

将您的子查询与c.State = s.State关联起来,因此我们可以在supplierconsumer表之间建立1对1的映射

© www.soinside.com 2019 - 2024. All rights reserved.