在一个SQL查询中区分,计数和排序

时间:2021-09-18 15:41:58

This is my first question on *, welcome everybody.

这是我关于*的第一个问题,欢迎大家。

I have a table:

我有一张桌子:

id   fk_user
1      1
2      1
3      3
4      2
5      3

And I would like to prepare an SQL query witch returns fk_user sorted by the number of occurrences in that table. For instance:

我想准备一个SQL查询,返回fk_user,并按该表中的出现次数排序。例如:

fk_user 1 occurs 3 times, so it will be first.
fk_user 2 occurs once, so it will be last.
fk_user 3 occurs twice, so it will be the second.

fk_user 1出现3次,所以它将是第一次。 fk_user 2出现一次,所以它将是最后一次。 fk_user 3出现两次,所以它将是第二次。

Result of that query should be:

该查询的结果应该是:

fk_user
1
3
2

2 个解决方案

#1


9  

select fk_user from 
xxx
group by fk_user
order by count(*) desc

#2


3  

Try this

尝试这个

SELECT fk_user FROM your_table
GROUP BY fk_user 
ORDER BY COUNT(*) DESC

#1


9  

select fk_user from 
xxx
group by fk_user
order by count(*) desc

#2


3  

Try this

尝试这个

SELECT fk_user FROM your_table
GROUP BY fk_user 
ORDER BY COUNT(*) DESC