我有test_scores
表,其中包含以下字段:
表架构:
id (number)
score1 (number)
score2 (number)
score3 (number)
score4 (number)
示例数据:
id score1 score2 score3 score4
1 10 05 30 50
2 05 15 10 00
3 25 10 05 15
预期结果集:
id col_name col_value
1 score4 50
2 score2 15
3 score1 25
这对于什么是好的SQL?(我正在使用MySQL。)
原始要求不包括行集中的列名称。我能够使用以下SQL获得结果:
SELECT A.id, MAX(A.score) AS max_score
FROM (
SELECT id, score1 as score FROM test_scores UNION
SELECT id, score2 as score FROM test_scores UNION
SELECT id, score3 as score FROM test_scores UNION
SELECT id, score4 as score FROM test_scores
) AS A
GROUP BY A.id
但是在结果集中引入了col_name,我感到难过......
答案 0 :(得分:5)
我使用以下SQL解决了这个问题:
SELECT id, GREATEST(score1, score3, score3, score4) AS col_value,
CASE GREATEST(score1, score3, score3, score4)
WHEN score1 THEN 'score1'
WHEN score2 THEN 'score2'
WHEN score3 THEN 'score3'
WHEN score4 THEN 'score4'
END AS col_name
FROM test_scores
Please let me know if there is a better solution.
答案 1 :(得分:2)
对于col_value,您需要使用GREATEST()
。
至于col_name,你可以这样做,但它不是很优雅:
SELECT id,
IF(score1 = col_value, 'score1',
IF(score2 = col_value, 'score2',
IF(score3 = col_value, 'score3', 'score4'))) AS col_name,
col_value
FROM (
SELECT *,
GREATEST(score1, score2, score3, score4) AS col_value
FROM test_scores
) AS helper
答案 2 :(得分:1)
解决方案的一部分(col_value
)可以是SQL MAX of multiple columns?。
答案 3 :(得分:1)
我更喜欢使用case语句的可读性,但我认为我只是为了踢而发布这个。
select GREATEST(score1, score2, score3, score4)
, ELT(FIELD(GREATEST(score1, score2, score3, score4), score1, score2, score3, score4), 'score1', 'score2', 'score3', 'score4')
from (
select 11 score1, 6 score2, 7 score3, 8 score4
) t