简体   繁体   中英

divide values in a Group By query

How is it possible to build a request like this (Sql Server 2008 R2) :
(I need an "Average Price" per result)

SELECT 
    CategoryId
  , SUM(Price) AS TotalPrice
  , SUM(Quantity) AS TotalQuantity
  -->, TotalPrice/TotalQuantity AS AveragePrice
FROM Products 
GROUP BY CategoryId

(if possible without recalculating one more times the two SUMs...)

without recalculating...

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
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

or you can use 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM