我从前两个查询中有两个表,试图将它们组合成一个表,以按州显示供应商总数和消费者总数。
我希望使用子查询来做到这一点,但是我无法弄清楚如何使用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
我从前两个查询中有两个表,试图将它们组合成一个表,以按州显示供应商总数和消费者总数。我希望使用子查询来完成它,...
-- 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
将您的子查询与c.State = s.State
关联起来,因此我们可以在supplier
和consumer
表之间建立1对1的映射