Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Calculating group percentage in SQL

I have a sample db table with columns ‘team’ and ‘result’ that stores match results ‘W’ (win) or ‘L’ (loose) for teams ‘A’ and ‘B’:

team|result
A   |W
A   |W
A   |W
A   |L
B   |W
B   |W
B   |L
B   |L

I can get the number of wins/losses per team by grouping by team and result:

sqlite> select team,result,count(*) from results group by team,result;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

A|L|1
A|W|3
B|L|2
B|W|2

However, I would also like to get a percentage of win/loss per team:

A|L|1|25
A|W|3|75
B|L|2|50
B|W|2|50

I have not succeeded in figuring out how to do this in SQL. I have managed to do this programmatically with a python programme that queries the db via the sqlite api, then loops over the result set and creates a variable to store the total count per group and then calculate percentage, etc

Can this be achieved directly in SQL?

Thanks

>Solution :

We can use SUM() as an analytic function:

SELCET team, result, COUNT(*) AS cnt,
       100.0 * COUNT(*) / SUM(COUNT(*)) OVER (PARTITION BY team) AS pct
FROM results
GROUP BY team, result;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading