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

问题描述 投票:0回答:2

我有一个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的最大值和最小值。

sql-server sum max aggregate min
2个回答
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

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;
© www.soinside.com 2019 - 2024. All rights reserved.