我有一个应用程序,其中包含音乐图表以展示顶部曲目(它显示前10名)。
但是,我试图限制图表,以便任何特定用户不能同时在热门图表上拥有多个曲目。
如果您需要更多信息,请告诉我们。
答案 0 :(得分:1)
您可以使用row_number()
函数,该函数提供一个在用户ID更改时重置的运行号码。然后,您可以在WHERE
子句中使用它来创建每用户限制:
SELECT * FROM (
SELECT COALESCE(sum(plays.clicks), 0),
row_number() OVER (PARTITION BY users.id ORDER BY COALESCE(sum(plays.clicks), 0) DESC),
users.id AS user_id,
tracks.*
FROM tracks
JOIN plays
ON tracks.id = plays.track_id
AND plays.created_at > now() - interval '14 days'
INNER JOIN albums
ON tracks.album_id = albums.id
INNER JOIN users
ON albums.user_id = users.id
GROUP BY users.id, tracks.id
ORDER BY 1 desc) sq1
WHERE row_number <= 2 LIMIT 10;