开发者

Quick SQL question! Sort by most occurences of an attribute

开发者 https://www.devze.com 2022-12-18 14:59 出处:网络
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开发者_

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

精彩评论

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

关注公众号