SQL Server:获取总和的最大值和最小值

时间:2019-03-13 10:14:04

标签: sql-server sum max aggregate min

我有一个ProductID产品的订购清单和订购数量。

例如:

ProductID Quantity
------------------
 1         5
 2         2
 3         5
 1         2
 3         4
 2         8

如何仅获得在SQL SERVER中销售最多和最少的产品的ProductID。我尝试过:

SELECT ProductID, SUM(Quantity) AS Total
FROM [Order Details]
GROUP BY ProductID
ORDER BY Total DESC

现在只需要Total的最大值和最小值。

2 个答案:

答案 0 :(得分:2)

使用公用表表达式或派生表获取sum,然后查询minmax

WITH CTE AS
(
    SELECT ProductID, sum(Quantity) as Total
    FROM [Order Details]
    GROUP BY ProductID
)

SELECT MIN(Total) As Lowest, MAX(Total) AS highest
FROM CTE

答案 1 :(得分:0)

我们可以在这里尝试两次使用ROW_NUMBER

WITH cte AS (
    SELECT ProductID, SUM(Quantity) AS Total,
        ROW_NUMBER() OVER (ORDER BY SUM(Quantity)) rn_least,
        ROW_NUMBER() OVER (ORDER BY SUM(Quantity) DESC) rn_greatest
    FROM [Order Details]
    GROUP BY ProductID
)

SELECT
    ProductID,
    CASE WHEN rn_least = 1
         THEN 'least' ELSE 'GREATEST' END AS label,
    Total
FROM cte
WHERE
    rn_least = 1 OR rn_greatest = 1
ORDER BY
    Total;