2016-03-21 16 views
2

Her gün bir şarkı için ölçülen bir puan içeren bir stats_by_dates tablosum var. Skorda en yüksek artışa sahip olan şarkıları nasıl bulabilirim? Bu tablodaki sütunlar: id, song_id, date, score.Zaman aralığındaki artışı bulmak için sorgu

Bu defa ne var ama sessiz doğru değil: Bu skor en çok artıran ilk 100 şarkı yerine skorla ilk 100 şarkı dönüyor

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 

. Çalışmayı tamamladıktan sonra, son 3 gün içinde en hızlı yükselen şarkıyı bulmak için sorguyu uygulamak istiyorum. Teşekkür ederim!

+0

açıkça bir örnek tablo veri beklenen sonuçları veriniz yapmak için. – AlexM

cevap

1

Sizi doğru anlarsam, bir şarkının ilk skorunu ve son skorunu almanız ve skorun zaman içinde nasıl değiştiğini gösterecek farkı (delta) hesaplamanız gerekir.

bu deneyin:

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

Bu mükemmel, teşekkürler! – jamesfzhang

İlgili konular