有個需求,需要組內排序,之前似乎從未接觸過此類排序,故查詢了一下,記錄sql執行結果。
表如下:
play_log:
日期 (fdate) | 用戶 ID (user_id) | 歌曲 ID (song_id) |
2022-01-08 | 10000 | 0 |
2022-01-16 | 10000 | 0 |
2022-01-20 | 10000 | 0 |
2022-01-25 | 10000 | 0 |
2022-01-02 | 10000 | 1 |
2022-01-12 | 10000 | 1 |
2022-01-13 | 10000 | 1 |
2022-01-14 | 10000 | 1 |
2022-01-10 | 10000 | 2 |
2022-01-11 | 10000 | 3 |
2022-01-16 | 10000 | 3 |
2022-01-11 | 10000 | 4 |
2022-01-27 | 10000 | 4 |
2022-02-05 | 10000 | 0 |
2022-02-19 | 10000 | 0 |
2022-02-07 | 10000 | 1 |
2022-02-27 | 10000 | 2 |
2022-02-25 | 10000 | 3 |
2022-02-03 | 10000 | 4 |
2022-02-16 | 10000 | 4 |
現在要統計,2022年每個月,聽的最多的前3首歌曲。
with new_table as(
select month(p.fdate),
ROW_NUMBER() OVER (PARTITION BY month(p.fdate) order by count(p.song_id) desc) as ranking,
count(p.song_id),
song_id
from play_log p where year(p.fdate)=2022 group by month(p.fdate), song_id
)select * from new_table where ranking < 4;
因為ranking窗口函數不能在本句內使用,故需要建立一個臨時表,然后再從表中篩選前3行的數據。結果輸出如下:
month(p.fdate) | ranking | count(p.song_id) | song_id |
1 | 1 | 4 | 0 |
1 | 2 | 4 | 1 |
1 | 3 | 2 | 3 |
2 | 1 | 2 | 0 |
2 | 2 | 2 | 4 |
2 | 3 | 1 | 1 |
用法:ROW_NUMBER() OVER (PARTITION BY COLUMN_1 ORDER BY COLUMN_2)?
COLUMN_1 是按哪一列分組,COLUMN_2是按哪一列進一步排序。?
練習習題:每個月Top3的周杰倫歌曲_牛客題霸_牛客網
?