below I have a query that will get the most common user agents for a site from a table of user agents and a linked table of ip addresses:
SELECT count(*) as
If you add with rollup
after your group by
clause, then you will get a row where string
is NULL
and num
is the total of all the browsers. You can then use that number to generate percentages.
I can't really imagine a single query doing the calculation and being more efficient than using with rollup
.
Yes you can:
select num, string, 100 * num / total as percent
from (
select count(*) as num, string
from useragent_ip
left join useragents on useragent_id = useragents.id
group by useragent_id) x
cross join (
select count(*) as total
from useragent_ip
left join useragents on useragent_id = useragents.id) y
order by num desc, string;
I removed the having num > 2
, because it didn't seem to make sense.