【问题标题】:is there an equivalent for max() in mysql that takes custom values?mysql 中是否有一个等效的 max() 可以接受自定义值?
【发布时间】:2022-01-03 13:32:38
【问题描述】:

观察表格

id priority value
1 high x
1 med k
1 low y
2 med k
2 low x

我需要一个函数来返回表中存在的最高优先级的 id 和 value,因此它应该在此处返回 x 表示 1 和 k 表示 2。有没有办法在不创建带有辅助列的中间表并在其上使用 max 的情况下做到这一点?

【问题讨论】:

  • 如果你使用MySql 8,你可以使用分析窗口函数。

标签: mysql aggregate-functions


【解决方案1】:

使用row_number,只要你使用的是MySql 8+,你就可以轻松完成

select Id, value 
from (
    select *, 
    Row_Number() 
      over(partition by id 
        order by case priority 
          when 'high' then 1
          when 'med' then 2 
          else 3 end
      ) pri
    from t
)t
where pri=1

如果您将优先级定义为 integer 值而不是 strings,您将获得更好的性能。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-17
    • 2010-09-16
    • 2016-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-16
    相关资源
    最近更新 更多