开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜