Divide by after Group query in SQL

Viewed 22

I can't quite figure this out. This query works, but I'd like to add a column that shows the percentage of the total.

SELECT f.name AS Acc., count(h.fair) AS Count
FROM holes h
JOIN fair f ON f.fair_id = h.fair
GROUP BY f.name

This results something similar to:

Acc. Count
A 5
B 6
C 4
D 5

I'd like to have it show

Acc. Count Percentage
A 5 25%.
B 6 30%.
C 4 20%.
D 5 25%.
1 Answers

Here's a solution with SQL Server.

with t2 as (
           select   col1     as "Acc."
                   ,count(*) as "Count"
           from     t
           group by col1
           ) 
select      "Acc."
           ,"Count"
           ,concat("Count"*100/(select sum("Count") from t2), '%') as Percentage
from        t2
Acc. Count Percentage
a 5 25%
b 6 30%
c 4 20%
d 5 25%

Fiddle

Related