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...)
How To Divide Query Output into Groups? You can divide query output into multiple groups with the GROUP BY clause. It allows you specify a column as the grouping criteria, so that rows with the same value in the column will be considered as a single group.
The SQL NTILE() is a window function that allows you to break the result set into a specified number of approximately equal groups, or buckets. It assigns each group a bucket number starting from one. For each row in a group, the NTILE() function assigns a bucket number representing the group to which the row belongs.
You can perform operations in the select statement. However, you cannot use the aliases of the SQL statement within it. So you need to do the calculation for col4 again. Just add sum(value1)/col5 as col6 .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With