【问题标题】:SQL to get max value from each group [duplicate]SQL从每个组中获取最大值[重复]
【发布时间】:2017-09-12 22:03:59
【问题描述】:

假设我有一张桌子

桌游

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 我想要最高评分的行。 IE。生成下表,其中 (***) 行被删除。

20170417 | 1         | 1       | 5
20170418 | 2         | 1       | 1
20170419 | 3         | 1       | 2
20170420 | 1         | 2       | 5

知道执行此操作的合理 SQL 查询是什么吗?

【问题讨论】:

  • 为什么 track_id = 3 和 user_id = 1 你期望 rating = 2,而不是 4?

标签: mysql sql


【解决方案1】:

假设您也想要 max 日期,请尝试以下操作:

SELECT track_id, user_id, MAX(rating), MAX(date)
FROM plays
GROUP BY track_id, user_id;

【讨论】:

    【解决方案2】:

    使用 MAX 内置函数和 GROUP by 子句:

        SELECT track_id, user_id, MAX(rating)
        FROM Your_table
        GROUP BY track_id, user_id;
    

    【讨论】:

    • 这可能是最简单的查询。如果这是附加要求,我还会添加 ORDER BY date
    • 他希望在您的答案中缺少的结果中有date
    【解决方案3】:
    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;
    

    【讨论】:

      【解决方案4】:

      如果您有 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
      

      【讨论】:

        猜你喜欢
        • 2020-01-13
        • 1970-01-01
        • 2020-11-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-06
        • 1970-01-01
        相关资源
        最近更新 更多