Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 262
serhio Avatar asked Dec 06 '13 10:12

serhio


People also ask

How do you divide query output into a group?

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.

How do you split a group in SQL?

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.

How do I separate two columns and GROUP BY in SQL?

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 .


1 Answers

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
like image 153
niyou Avatar answered Oct 01 '22 15:10

niyou