1

我有两个包含以下记录的表:

客户:

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 行返回

“约翰”、“澳大利亚”

“马克”、“美国”

但我只需要知道,是否可以通过更简单的方式完成。一旦还要求退还全部数量,情况就变得复杂了。

4

3 回答 3

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
于 2013-05-22T13:57:08.527 回答
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 )
于 2013-05-22T13:02:52.213 回答
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
于 2013-05-22T11:28:45.737 回答