mysql中的行最大值
我的mysql表中有5列: name s1 s2 s3 s4 A 1 2 3 4 B 15 6 7 8 名称s1 s2 s3 s4 A 1234 B 15 6 7 8 我想计算一行中s1、s2、s3、s4的最大值所在的列名和值,即 name col value A s4 4 B s1 15 名称列值 A s4.4 B s1 15 我不能使用max,因为它计算列最大值。我该怎么做 PS:模式不能更改,因为在所有其他用例中,我必须按名称显示信息mysql中的行最大值,mysql,Mysql,我的mysql表中有5列: name s1 s2 s3 s4 A 1 2 3 4 B 15 6 7 8 名称s1 s2 s3 s4 A 1234 B 15 6 7 8 我想计算一行中s1、s2、s3、s4的最大值所在的列名和值,即 name col value A s4 4 B s1 15 名称列值 A s4.4 B s1 15 我不能使用max,因为它计算列最大值。我该怎么做 PS:模式不能更改,因为在所有其他用例中,我必须按名称显示信息 提前感谢。您
提前感谢。您可以使用此选项,但请注意,在这种情况下,如果您在两个不同的列中获得最大值,您将获得空值。如果您想要获得其他值,我们可以在这种情况下更改此选项
select name,
case when s1>s2 and s1>s3 and s1>s4 then 's1'
when s2>s1 and s2>s3 and s2>s4 then 's2'
when s3>s1 and s3>s2 and s3>s4 then 's3'
when s4>s1 and s1>s2 and s1>s3 then 's4' as col
case when s1>s2 and s1>s3 and s1>s4 then s1
when s2>s1 and s2>s3 and s2>s4 then s2
when s3>s1 and s3>s2 and s3>s4 then s3
when s4>s1 and s1>s2 and s1>s3 then s4 as value
from my_table
表的正确数据结构如下所示:
name | column | value
-----|--------|------
A | s1 | 1
A | s2 | 2
A | s3 | 3
A | s4 | 4
B | s1 | 15
B | s2 | 6
B | s3 | 7
B | s4 | 8
select *
from tablename
where (name, value) in (select name, max(value)
from tablename
group by name)
然后您的查询将如下所示:
name | column | value
-----|--------|------
A | s1 | 1
A | s2 | 2
A | s3 | 3
A | s4 | 4
B | s1 | 15
B | s2 | 6
B | s3 | 7
B | s4 | 8
select *
from tablename
where (name, value) in (select name, max(value)
from tablename
group by name)
但是,您希望如何管理一个tie(具有相同最大值的两列?)
如果无法更改数据结构,您仍然可以做一些事情,获得最大值很容易:
select name, greatest(s1, s2, s3, s4)
from tablename
但同时获取列名有点棘手:
select
name,
max_value,
case when p=1 then 's1'
when p=2 then 's2'
when p=3 then 's3'
when p=4 then 's4'
end as col_name
from (
select
name,
greatest(s1, s2, s3, s4) as max_value,
field(greatest(s1, s2, s3, s4), s1, s2, s3, s4) as p
from
tablename
) s
或者这个:
select
name,
greatest(s1, s2, s3, s4) as max_value,
substring_index(substring_index('s1,s2,s3,s4', ',', field(greatest(s1, s2, s3, s4), s1, s2, s3, s4)), ',', -1) as p
from
更改您的数据库结构mysql中是否有类似pivot的内容?@RogueCoder group by用作mysql中的pivot。是否有办法将这两个case语句组合成1,即case返回多个值?此外,concat是一种方法,但我不想这样做。每个案例都给你一列,因为你想要两个不同的列,你需要两个案例。你可以将它们组合起来,用逗号或其他字符分隔值,但你会在一列中收到它们,在你的问题中,你问了两个不同的列。我已经更新了问题。由于其他功能要求,我无法更改表结构。@proprius您是否尝试过我的第二种解决方案?是。。我现在使用的是最大的函数,但我不能使用子字符串索引部分。。这是因为我的列名可能有
,
或,
@proprius,如果你的列名可能有,
这是个问题。。。您可以使用任何其他字符,例如|
?然后您可以使用子字符串索引(子字符串索引('s1 | s2 | s3 | s4','|'),字段(最大值(s1,s2,s3,s4),s1,s2,s3,s4)),'|',-1)
不确定性总是存在的。为了避免这种情况,我在列上使用if-else