说我有一张桌子
表格播放
date | track_id | user_id | rating
-----------------------------------------
20170416 | 1 | 1 | 3 (***)
20170417 | 1 | 1 | 5
20170418 | 2 | 1 | 1
20170419 | 3 | 1 | 4
20170419 | 3 | 1 | 2 (***)
20170420 | 1 | 2 | 5
我想要做的是每个唯一的track_id,user_id我想要最高评级行。即在下面的表中生成(***)行被删除。
20170417 | 1 | 1 | 5
20170418 | 2 | 1 | 1
20170419 | 3 | 1 | 2
20170420 | 1 | 2 | 5
知道一个合理的SQL查询是做什么的吗?
答案 0 :(得分:4)
使用MAX内置函数和GROUP by子句:
SELECT track_id, user_id, MAX(rating)
FROM Your_table
GROUP BY track_id, user_id;
答案 1 :(得分:1)
假设您也想要max
日期,请尝试以下操作:
SELECT track_id, user_id, MAX(rating), MAX(date)
FROM plays
GROUP BY track_id, user_id;
答案 2 :(得分:1)
select * from [table] t1
inner join
(
select track_id, user_id, max(rating) maxRating
from [table]
group by track_id, user_id
) tmp
on t1.track_id = tmp.track_id
and t1.user_id = tmp.user_id
and t1.rating = tmp.maxRating;
答案 3 :(得分:1)
如果您有GROUP BY
子句中未提及的额外列,则可以使用以下子查询:
SELECT track_id,user_id,rating --, other columns you want to display
FROM(
SELECT track_id, user_id, rating,ROWNUMBER() OVER(PARTITION BY track_id, user_id ORDER BY rating DESC) as RN --,Other columns which you want to display
FROM Your_table
) X
WHERE X.RN=1