Consider this simple query:
SELECT
year(t.date) AS y,
month(t.date) AS m,
t.person_id AS id,
count(*) AS freq
FROM
table t
WHERE
t.date>='2013-01-01' AND t.date<='2013-06-30'
GROUP BY y, m, id
This yields something like this:
y m id freq
------------------
2013 1 100 2
2013 1 101 7
2013 1 102 1
2013 2 100 5
2013 2 101 4
2013 2 102 11
...
I would like to add a column that contains the percent of freq with respect to the sum of freq in each month, e.g.:
y m id freq perc
-----------------------
2013 1 100 2 20
2013 1 101 7 70
2013 1 102 1 10
2013 2 100 5 25
2013 2 101 4 20
2013 2 102 11 55
...
My solution so far is to add this to the select clause:
count(*) * 100 / (SELECT count(*) FROM table WHERE year(date)=y AND month(date)=m) AS perc
But I would like to avoid a sub-select, especially since all necessary values are already present in the first query's result. This would require an aggregation of aggregated values, but I don't know how to do this. Any ideas?