我的mysql表中有5列:
name s1 s2 s3 s4 A 1 2 3 4 B 15 6 7 8
我想计算一行中s1,s2,s3,s4中最大值的列名和值,即
name col value A s4 4 B s1 15
我不能使用max,因为它计算列的最大值。我该怎么做?
PS:架构无法更改,因为在所有其他用例中,我必须明智地显示信息。
提前致谢。
答案 0 :(得分:3)
表格的正确数据结构如下:
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)
但是你想如何管理一个平局(两列具有相同的最大值?)
如果你无法改变你的数据结构,你仍然可以做些事情,获得最大值很容易:
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
答案 1 :(得分:0)
你可以使用它,但请注意,在这种情况下,如果你在两个不同的列中得到最大值,你将获得空值,如果你想获得其他值,我们可以在这种情况下改变它
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