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

前端 未结 3 2002
难免孤独
难免孤独 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条回答
  • 2020-12-01 01:43
    SELECT Category, COUNT(*) AS Total , (COUNT(*) / (SELECT COUNT(*) FROM Item WHERE Department='Popular')) * 100 AS 'Percentage to all items', 
    FROM Item
    WHERE Department='Popular'
    GROUP BY Category;
    

    I'm not sure of the MySql syntax, but you can use a sub-query as shown.

    0 讨论(0)
  • 2020-12-01 01:58

    This should do it:

    SELECT I.category AS category, COUNT(*) AS items, COUNT(*) / T.total * 100 AS percent
    FROM Item as I,
         (SELECT COUNT(*) AS total FROM Item WHERE Department='Popular') AS T
    WHERE Department='Popular'
    GROUP BY category;
    
    0 讨论(0)
  • 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).

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