Quick SQL question! Sort by most occurences of an attribute
I have two tables as such:
Categories: ID - Name - Desc
Items ID - Name - CategoryID - Desc - Price
I want a query that returns a list of categories ranked by the most occurences in the items t开发者_如何学Cable.
This should do the trick:
SELECT c.ID, c.Name, count(i.ID)
FROM Categories c
LEFT JOIN Items i on (c.ID=i.CategoryID)
GROUP BY c.ID
ORDER BY count(i.ID)
SELECT
CategoryID, count(*)
FROM
items
GROUP BY
CategoryID
ORDER BY
2 DESC
You can then join to categories to get their names.
精彩评论