这是我的两张桌子:
歌曲:
+--------+---------------------+
| SongID | SongDeviceID |
+--------+---------------------+
| 3278 | 1079287588763212246 |
| 3279 | 1079287588763212221 |
| 3280 | 1079287588763212230 |
+--------+---------------------+
投票:
+--------+--------+
| SongID | UserID |
+--------+--------+
| 3278 | 71 |
| 3278 | 72 |
| 3279 | 71 |
+--------+--------+
我正在尝试计算votes
表中的条目数(针对每个唯一SongID
,并返回最多的条目SongDeviceID
。
这是我到目前为止所做的:
SELECT Songs.SongDeviceID, COUNT(*) FROM Votes INNER JOIN Songs ON Votes.SongID = Songs.SongId GROUP BY Votes.SongID, Songs.SongDeviceID ORDER BY count(*) DESC
返回:
+---------------------+----------+
| SongDeviceID | Count(*) |
+---------------------+----------+
| 1079287588763212246 | 2 |
| 1079287588763212221 | 1 |
+---------------------+----------+
更新 查询已更新,以便获取SongDeviceID,但我仍然需要帮助才能返回第一行。
答案 0 :(得分:1)
第一次
SELECT SongID,COUNT(*) from votes GROUP BY SongID order by count(*) DESC LIMIT 1
然后你想要歌曲设备名称
SELECT SongID,COUNT(*),SongDeviceID
from
votes
left join
Songs on votes.songid = song.songid
GROUP BY
SongID
order by
count(*) DESC LIMIT 1
答案 1 :(得分:1)
试试这个
SELECT Songs.SongDeviceID, COUNT(*) FROM Votes INNER JOIN Songs ON Votes.
SongID = Songs.SongId GROUP BY Votes.SongID, Songs.SongDeviceID ORDER BY count(*)
DESC LIMIT 1
答案 2 :(得分:0)
select top 1
S.SongDeviceID, COUNT(distinct V.UserID) as 'UserVotes'
from
Songs as S
join
Votes as V on V.SongID = S.SongID
group by
S.SongDeviceID
order by
UserVotes DESC