Getting percentage of “Count(*)” to the number of all items in “GROUP BY”

前端 未结 3 2023
难免孤独
难免孤独 2020-12-01 01:37

Let\'s say I need to have the ratio of "number of items available from certain category" to "the number of all items". Please consider a

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-01 02:00

    SET @total=0;
    
    SELECT Category, count(*) as Count, count(*) / @total * 100 AS Percent FROM (
        SELECT Category, @total := @total + 1
        FROM Item
        WHERE Department='Popular') temp
    GROUP BY Category;
    

    An advantage of doing it this way is you do not have to duplicate the WHERE condition, which is a ticking time bomb the next time someone comes by to update the condition, but doesn't realize it's in two different places.

    Avoiding the duplicate WHERE condition also improves readability, especially if your WHERE is more complex (with multiple joins, etc).

提交回复
热议问题