如何将这两个SQL查询合并为一个?

时间:2017-11-01 22:14:32

标签: sql

显示请求数量超过要约数量的城市。

我已经进行了这两个查询,以显示每个城市的消费者有多少请求,然后是每个城市中有优惠的供应商的请求。是的,这是实验室的一部分,我得到了每个输出,但我现在已经坚持了2个小时,我已经尝试了所有我能想到的,这也是最后一个问题。

SELECT COUNT(c.Con_ID) 'Requests', city
FROM tb_requests r, Tb_Consumer c, Tb_Product p
WHERE r.Con_ID = c.Con_ID
  AND r.Prod_ID = p.Prod_ID
  ANd p.Name = 'computer'
  group by city

SELECT COUNT(s.supp_id) 'Offers', city
FROM Tb_offers o, Tb_supplier s, Tb_Product p
WHERE o.supp_ID = s.supp_ID
  AND o.Prod_ID = p.Prod_ID
  ANd p.Name = 'computer'
  GROUP By city

输出如下:

Number      city
----------- ------------------------------
2           New York
4           Wausau

(2 row(s) affected)

Number      city
----------- ------------------------------
2           Chicago
1           London
4           Madison
2           Stevens Point
3           Wausau

(5 row(s) affected)

正确的输出应该是这个(它们在一起):

City                           Computer Offers Computer Requests
------------------------------ --------------- -----------------
Wausau                         3               4

(1 row(s) affected)

非常感谢你!

1 个答案:

答案 0 :(得分:0)

当您提出SQL问题时,请添加您的DBMS(例如MySQL,SQL Server,PostgreSQL等)

这不只是困扰你,但是使用SQL语法可能会因数据库而发生很大变化。

说完之后,我将使用ANSI SQL(应该适用于每个不错的数据库):

SELECT t1.city, Offers, Requests
FROM (
    SELECT COUNT(c.Con_ID) Requests, city
    FROM tb_requests r, Tb_Consumer c, Tb_Product p
    WHERE r.Con_ID = c.Con_ID
    AND r.Prod_ID = p.Prod_ID
    ANd p.Name = 'computer'
    group by city
    ) t1
INNER JOIN (
    SELECT COUNT(s.supp_id) Offers, city
    FROM Tb_offers o, Tb_supplier s, Tb_Product p
    WHERE o.supp_ID = s.supp_ID
    AND o.Prod_ID = p.Prod_ID
    ANd p.Name = 'computer'
    GROUP By city
    ) t2
    ON t1.city = t2.city
WHERE Requests > Offers

如果你想要更干净的东西,这应该完全相同:

SELECT city, COUNT(s.supp_id) Offers, COUNT(c.Con_ID) Requests
FROM Tb_Product p
    LEFT JOIN Tb_offers o ON p.Prod_ID = o.Prod_ID
        LEFT JOIN Tb_supplier s ON o.supp_ID = s.supp_ID
    LEFT JOIN tb_requests r ON p.Prod_ID = r.Prod_ID
        LEFT JOIN Tb_Consumer c ON r.Con_ID = c.Con_ID
WHERE p.Name = 'computer'
GROUP BY city
HAVING COUNT(c.Con_ID) > COUNT(s.supp_id)