Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Average of a Sum in Mysql query

I am having some problems creating a query that gives me the average of a sum. I read a few examples here in stackoverflow and couldn't do it. Can anyone help me to understand how to do this please? This is the data I have:

Transaction_x0020_Number  Product_x0020_Code  Sales_x0020_Value  Date        Cashier
000356                    350                 24.99              2010-06-04  131    
000356                    726                 32.99              2010-06-04  131    
000357                    350                 24.99              2010-06-04  131    
000358                    350                 24.99              2010-06-04  131    
000358                    360                 24.99              2010-06-04  131    
000770                    703                 69.99              2010-06-04  130    
000771                    726                 32.99              2010-06-04  130    
000772                    1126                5                  2010-06-04  130    
000773                    482                 32.99              2010-06-04  130    
000774                    600                 32.99              2010-06-04  130    
000775                    350                 24.99              2010-06-04  130    

Basically I need the average transaction value by cashier. I can't run a basic avg because it will take all rows but each transaction can have multiple rows. At the end I want to have:

Cashier| Average|  
131    | 44.31  |(Which comes from the sum divided by 3 transactions not 5 rows)  
130    | 33.15  |  
etc.  

This is the query I have to SUM the transactions but don't know how or where to include the AVG function.

SELECT `products`.`Transaction_x0020_Number`, 
       Sum(`products`.`Sales_x0020_Value`) AS `SUM of Sales_x0020_Value`, 
       `products`.`Cashier`   
  FROM `products`
GROUP BY `products`.`Transaction_x0020_Number`, `products`.`Date`, `products`.`Cashier`
  HAVING (`products`.`Date` ={d'2010-06-04'})  

Any help is appreciated.

like image 397
chupeman Avatar asked Jun 07 '10 19:06

chupeman


1 Answers

SELECT Cashier,
       Sum(Sales_x0020_Value) / COUNT(DISTINCT Transaction_x0020_Number) AS 'avg'
FROM products 
WHERE Date = {d'2010-06-04'}
GROUP BY Cashier
like image 73
Vitalii Fedorenko Avatar answered Nov 11 '22 02:11

Vitalii Fedorenko