Quick SQL query! Sort by most attribute occurrences

Hi guys, I have two tables:

Categories: ID - Name - Desc

Elements ID - Name - CategoryID - Desc - Price

I need a query that returns a list of categories ranked by most occurrences in the element table

+3
source share
2 answers

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)
+8
source
SELECT 
  CategoryID, count(*)
FROM 
  items
GROUP BY 
  CategoryID
ORDER BY 
  2 DESC

You can then join the categories to get their names.

+1
source

Source: https://habr.com/ru/post/1730982/


All Articles