具有列名的多列的最大值?

2021-11-20 00:00:00 sql mysql

关于如何从多列中返回最大值以及列名,我已经探索了许多问题和答案.但我还没有解决问题这里在这个问题中将解释:

I have explored many questions and answers regarding how to return the greatest values from multiple columns along with column name. But I have not solved the problem here in this question will explain:

多列的SQL MAX?

但我不知道如何找出具有最大价值的列名?有什么想法吗?

But I don't know how to figure out the column name having greatest value? Any ideas?

推荐答案

您可以使用 GREATEST 函数在所有列中找到最大值:

You can use GREATEST function to find the maximum value among all columns:

SELECT @var_max_val:= GREATEST(col1, col2, col3, ...) AS max_value,
       CASE @var_max_val WHEN col1 THEN 'col1'
                         WHEN col2 THEN 'col2'
                         ...
       END AS max_value_column_name
FROM table_name
WHERE ...

相关文章