我试图在一年中的某个月内找到用户首次听到的歌曲
我正在使用以下数据
user-id date song
....... ....... ......
1 2017-9-30 song1
1 2017-9-10 song1
1 2017-3-12 song2
1 2017-9-01 song1
1 2017-12-31 song1
1 2017-09-12 song3
1 2017-10-11 song1
1 2017-09-09 song5
1 2017-10-08 song4
2 2017-07-12 song1
2 2017-12-31 song3
2 2017-10-12 song5
3 2017-10-11 song1
3 2017-10-09 song7
3 2017-10-08 song2
3 2017-07-12 song2
我想获得以下输出
user-id year month song count
....... ...... ...... ..... ......
1 2017 9 song1 3
我尝试过以下查询,但是我按降序获取所有数据,而我无法选择最顶层的数据
SELECT YEAR(date) AS year, MONTH(date) AS month,song,count(song) c
FROM table where id=1 and year(dt)=2017 and month(dt)=9
GROUP BY YEAR(date), MONTH(date) ,song ORDER BY c DESC
我甚至尝试过使用
SELECT d.*
FROM (SELECT id,year(date) y,month(date) m,count(song) as c,
ROW_NUMBER() OVER (PARTITION BY month(date) ORDER BY COUNT(song) DESC) as seqnum
FROM table where id=1 and month(date)=9
GROUP BY month(date),year(date) song
) d
WHERE seqnum = 1
ORDER BY c, dt DESC ;
它会抛出错误
编译语句时出错:FAILED:ParseException行5:37无关输入'歌'期待'附近''
答案 0 :(得分:2)
您可以使用LIMIT
:
SELECT YEAR(date) AS year, MONTH(date) AS month,song,count(song) c
FROM table
GROUP BY YEAR(date), MONTH(date) ,song
ORDER BY c DESC
LIMIT 1