我有两张包含以下记录的表:
客户端:
cid | cname | ccountry
-----------------------
1 | John | Australia
2 | Mark | USA
3 | Liz | England
订单:
oid | cid | oquantity
---------------------
1 | 1 | 100
2 | 1 | 100
3 | 2 | 50
4 | 2 | 150
5 | 3 | 50
6 | 3 | 100
我需要查找拥有最大订单数量的客户名称。我运行以下查询并获得正确的结果。
select cname, ccountry
from Clients
where cid in
(select cid
from Orders
group by cid
having sum(oquantity) = (select max(amount) from
(select sum(oquantity) amount
from Orders
group by cid)t1))
返回2行
'约翰','澳大利亚'
'马克','美国'
但我只需要知道,是否可以通过更简单的方式完成。一旦总量也需要返还,它就变得复杂了。
答案 0 :(得分:0)
SELECT c.cname, c.ccountry, SUM(oquantity) AS total_qtty
FROM Clients c
INNER JOIN Orders o ON (o.cid = c.cid)
GROUP BY c.id
ORDER BY total_qtty DESC
LIMIT 2
答案 1 :(得分:0)
我减少了2
子查询。
SELECT
clients.cid,
cname,
ccountry
FROM Orders,
Clients
WHERE orders.cid = clients.cid
GROUP BY clients.cid
HAVING SUM(orders.oquantity) = (SELECT
SUM(oquantity) AS amount
FROM Orders
GROUP BY cid
ORDER BY amount DESC
LIMIT 1 )
答案 2 :(得分:0)
尝试:
select cname, ccountry, sum(oquantity)
FROM Clients c
INNER JOIN Orders o ON (o.cid = c.cid)
where c.cid in
(
select cid from Orders group by cid
having sum(oquantity) = (
select max(amount) from (
select sum(oquantity) amount from Orders group by cid)t1))
GROUP BY c.cid