如何构建这样的请求(Sql Server 2008 R2):
(我需要每个结果的“平均价格”)
SELECT
CategoryId
, SUM(Price) AS TotalPrice
, SUM(Quantity) AS TotalQuantity
-->, TotalPrice/TotalQuantity AS AveragePrice
FROM Products
GROUP BY CategoryId
(如果可能的话,不再重新计算两个SUM ...)
答案 0 :(得分:5)
不重新计算...
SELECT *, A.TotalPrice / A.TotalQuantity AS AveragePrice
FROM (SELECT
CategoryId
, SUM(Price) AS TotalPrice
, SUM(Quantity) AS TotalQuantity
FROM Products
GROUP BY CategoryId) AS A
答案 1 :(得分:1)
SELECT CategoryId,
SUM(Price) AS TotalPrice,
SUM(Quantity) AS TotalQuantity,
(SUM(Price) * 1.0 / SUM(Quantity) * 1.0) AS AveragePrice
FROM Products
GROUP BY CategoryId
或者您可以使用CTE
WITH cte
AS
(
SELECT CategoryId,
SUM(Price) AS TotalPrice,
SUM(Quantity) AS TotalQuantity
FROM Products
GROUP BY CategoryId
)
SELECT CategoryId,
TotalPrice,
TotalQuantity,
TotalPrice / TotalQuantity * 1.0 AveragePrice
FROM cte