选择订购了最多产品的客户?

时间:2016-12-31 04:41:42

标签: mysql sql

我正在尝试查询以查找从下表中订购了最多数量产品的客户!

mysql> select * from ORDERS;
+---------+---------+------------+-----+
| CUSTNUM | PRODNUM | DATE       | QTY |
+---------+---------+------------+-----+
|  125216 |    2323 | 2016-03-21 |   2 |
|  136101 |    2357 | 2016-03-21 |   5 |
|  136101 |    2357 | 2016-10-12 |   1 |
|  136101 |    2357 | 2016-11-25 |   5 |
|  136101 |    3737 | 2016-10-12 |  10 |
|  136101 |    9193 | 2016-11-25 |   5 |
|  182764 |    2357 | 2015-03-21 |  12 |
|  182764 |    2357 | 2016-05-12 |  10 |
|  212836 |    3737 | 2015-09-16 |   6 |
|  455566 |    4143 | 2016-02-09 |  10 |
|  455566 |    4143 | 2016-05-12 |  10 |
+---------+---------+------------+-----+

预期结果

+-------------+------------------+
| CUSTNUM     | quantity_ordered |
+-------------+------------------+
| 136101      |               26 |
+-------------+------------------+

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

使用group by子句。

欲了解更多信息, 请参考一些tutorials

或阅读official docs

SELECT  CUSTNUM, SUM(QTY) s FROM ORDERS GROUP BY CUSTNUM 
ORDER BY s DESC LIMIT 1 

SQLfiddle