简体   繁体   中英

SQL average Percentage by group

I have table1 with some sample record (would have more than 100 records)

lastname    courtesy    
Lane          3  
Lane          4  
Lane          5  
Lane         12   
Santana       4  
Santana       5  

My query to get the ave percent group by lastname and did not group by lastname
you can see Lane and Santana still not group.
Please correct the query. Thank you.


SELECT
  lastname,
  courtesy,
  percentage = AVG(courtesy) * 100 / SUM(AVG(courtesy)) OVER (PARTITION BY lastname)
FROM echo
GROUP BY
  lastname, courtesy

the results

lastname    courtesy    percentage
Lane         3           12
Lane         4           16
Lane         5           20
Lane         12          50
Santana      4           44
Santana      5           55

the results look like this

lastname    percentage
Lane         16        (4/24)
Satana       22        (2/9)
count (lastname) / sum (courtesy)  group by lastname

I think this is the logic that you want:

SELECT lastname,
       SUM(SUM(courtesy)) OVER (ORDER BY lastname),
       COUNT(*) * 1.0 / SUM(courtesy)
FROM echo
GROUP BY lastname;

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