2016-03-21 12 views
2

私はstats_by_datesのテーブルを持っています。このテーブルには、曲ごとに毎日測定されたスコアが含まれています。スコアが最も高い曲を見つけるにはどうすればよいですか?時間の経過とともに増加を見つけるクエリ

この表の列は次のとおりです:idsong_iddatescore

これは私がこれまで持っているものですが、それは静かな権利ではありません:これは、スコアの最も高い増加で上位100曲の代わりにスコアで上位100曲を返して

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 

。それがうまくいけば、過去3日間で最も速く上昇する曲を探すためにクエリを適用したいと思う。ありがとうございました!

+0

はそれを明確に、例えばテーブルデータに期待される結果を提供してくださいようにするには。 – AlexM

答えて

1

私があなたに合ったら、曲の最初のスコアと最後のスコアを取得し、時間の経過とともにスコアがどのように変化したかを表す差(デルタ)を計算する必要があります。

これを試してみてください:

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 
+0

これは完璧です、ありがとう! – jamesfzhang

関連する問題