I have an app that includes music charts to showcase the top tracks (it shows the top 10).
However, I'm trying to limit the charts so that any particular user cannot have more than 2 tracks on the top charts at the same time. If Artist A normally would have 4 of the top 10 slots, only the top 2 tracks by Artist A would be shown (and #11 and #12 on the list would be bumped up 2 spots each, presuming they aren't also by Artist A of course).
So, let's say this is the top charts section right now:
- Song A by Artist A
- Song B by Artist B
- Song C by Artist A
- Song D by Artist C
- Song E by Artist D
- Song F by Artist E
- Song G by Artist F
- Song H by Artist A
- Song I by Artist A
- Song J by Artist G
I would like to limit the SQL results so #8 and #9 aren't included (because only up to 2 tracks per artist would be allowed in the query results) and the list would instead become:
- Song A by Artist A
- Song B by Artist B
- Song C by Artist A
- Song D by Artist C
- Song E by Artist D
- Song F by Artist E
- Song G by Artist F
- Song J by Artist G
- Song K by Artist H (previously #11)
- Song L by Artist I (previously #12)
FYI, I'm using Postgres, and this is what I have right now. It counts plays per track in the last 14 days to generate the top 10 list. I would like to modify it to get the desired limitation noted above.
def self.top_tracks_past14(max=3)
Track.find_by_sql(["select COALESCE(sum(plays.clicks), 0), tracks.*
from tracks
left 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 tracks.id
order by 1 desc limit ?", max])
end