我有一个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的最大值和最小值。
使用公用表表达式或派生表来获取sum
,然后查询min
和max
:
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
我们可以尝试两次使用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;