How can I get the percentage of total rows with mysql for a group?

后端 未结 2 1362
星月不相逢
星月不相逢 2021-01-20 20:41

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          


        
相关标签:
2条回答
  • 2021-01-20 20:55

    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.

    0 讨论(0)
  • 2021-01-20 20:59

    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.

    0 讨论(0)
提交回复
热议问题