我有一张stats_by_dates
表,其中包含每天为一首歌测量的分数。如何找到分数增幅最高的歌曲?
此表格中的列为:id
,song_id
,date
,score
。
这是我到目前为止所做的,但它并不安静:
select song_id, date, score - coalesce(lag(score) over (partition by song_id order by date desc), 0) as delta
from stats_by_dates
group by song_id, date, score
order by score desc limit 100
这是按分数返回前100首歌曲,而不是排名最高的前100首歌曲。一旦我开始工作,我也想应用查询来查找过去3天内最快的上升歌曲。谢谢!
答案 0 :(得分:1)
如果我找对你,你需要得到一首歌的第一个得分和最后得分,并计算差异(delta),这将代表得分随时间变化的方式。
试试这个:
SELECT DISTINCT
song_id,
-- the first score of a song
first_value(score) OVER (PARTITION BY song_id ORDER BY date ASC) as first_score,
-- the last score of a song
first_value(score) OVER (PARTITION BY song_id ORDER BY date DESC) as last_score,
-- the difference (delta) between the first and the last scores
(first_value(score) OVER (PARTITION BY song_id ORDER BY date DESC) - first_value(score) OVER (PARTITION BY song_id ORDER BY date ASC)) as delta
FROM stats_by_dates
WHERE date > now() - INTERVAL '3 day' -- get score for the last 3 days
ORDER BY delta DESC LIMIT 100