使用选择总和查询来找到总和的最大值和最小值

时间:2019-05-02 04:12:35

标签: mysql

我正试图在mysql中回答这个问题...“什么产品卖得最多/最少?我想将max和min函数添加到我的selet语句中,但不确定如何或在何处。

这是我目前正在尝试将max和min语句添加到的内容

SELECT prod_nbr,sum(sls_qty) AS sls_qty
FROM total_sales
GROUP BY prod_nbr
ORDER BY sls_qty DESC;

2 个答案:

答案 0 :(得分:1)

假设您使用的是MySQL 8+,这是使用ROW_NUMBER的选项:

SELECT
    prod_nbr,
    sls_qty,
    IF(rn_min = 1, 'min', 'max') type
FROM
(
    SELECT prod_nbr, SUM(sls_qty) AS sls_qty,
        ROW_NUMBER() OVER (ORDER BY SUM(sls_qty)) rn_min,
        ROW_NUMBER() OVER (ORDER BY SUM(sls_qty) DESC) rn_max
    FROM total_sales
    GROUP BY prod_nbr
) t
WHERE 1 IN (rn_min, rn_max)
ORDER BY sls_qty;

答案 1 :(得分:0)

对两个查询进行合并。

SELECT 'max' AS TYPE,
       prod_nbr,
       sum(sls_qty) AS sls_qty
FROM total_sales
GROUP BY prod_nbr
ORDER BY sls_qty DESC
UNION ALL
SELECT 'min' AS TYPE,
       prod_nbr,
       sum(sls_qty) AS sls_qty
FROM total_sales
GROUP BY prod_nbr
ORDER BY sls_qty ASC