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
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.
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;
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).