我有一个用户表,其中包含他们投票的用户ID,如下所示:
uid | voted_for
1 | 3
2 | 3
3 | 1
我的目标是根据有多少人投票支持uid订购uid。但我不知道该怎么做。
所以最终的结果是:
uid | Total_Votes
3 | 2
1 | 1
2 | 0
希望您能帮助解释为此构建SQL的最佳方法。
答案 0 :(得分:2)
也许这样的事情将有助于自己加入表格:
SELECT u.*, voted_for_cnt
FROM users u
LEFT JOIN (
SELECT voted_for, count(1) voted_for_cnt
FROM users
GROUP BY voted_for
) t ON u.uid = t.voted_for
ORDER BY t.voted_for_cnt DESC
答案 1 :(得分:1)
这个简单的查询将产生您请求的输出:
select voted_for as uid, count(*) as total_votes
from users
group by 1
order by 2 desc
如果您想要输出中有关每个用户的所有数据,请将用户加入自身:
select u.*, count(v.uid) as total_votes
from users u
left join users v on v.voted_for = u.uid
group by 1,2,3,4,5 -- put as many numbers here as there are columns in the users table
order by total_votes desc
如果没有人投票给用户,则第二个查询将total_votes
得分为零。
或者,您只能选择所需的列:
select u.uid, u.name, count(v.uid) as total_votes
from users u
left join users v on v.voted_for = u.uid
group by 1,2
order by 3 desc
```
要仅返回获奖者,请执行以下操作:
select u.uid, u.name, count(*) as total_votes
from users u
left join users v on v.voted_for = u.uid
group by 1,2
having count(*) = (
select max(c) from (
select count(*) as c from users group by voted_for))
order by 3 desc