Ordering by COUNT() in SQL

社会主义新天地 提交于 2019-12-13 02:14:02

问题


Let's say I have a database table like this:

users
------
id
email
referrerID

How could I sort by the members with the most referrals? I was trying something along the lines of:

SELECT id,email FROM users WHERE 1 ORDER BY COUNT(referrerID) DESC;

But this does not seem to work. What is wrong?

I think that the default value 0 may also be affecting this somehow?


回答1:


Following clarification

SELECT referrerID,
       COUNT(id) as Num
FROM   users
GROUP  BY referrerID
ORDER  BY CASE
            WHEN referrerID = 0 THEN -1
            ELSE COUNT(id)
          END DESC;  


来源:https://stackoverflow.com/questions/7478710/ordering-by-count-in-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!