我有表:
评分:
id | one | two | three
1 | 12 | 3 | 7
2 | 11 | 30 | 3
3 | 8 | 14 | 4
如何从这些字段(一、二、三)中获取 SQL MAX 值?对于此示例,这是30。
SELECT MAX(field) FROM (
SELECT one AS field FROM table
UNION
SELECT two AS field FROM table
UNION
SELECT three AS field FROM table
) AS t
select GREATEST(max(one), max(two), max(three)) as maximum
from table;
您可以像这样取消透视数据:
select max(value)
from
(
select id, 'one' col, one value
from yourtable
union all
select id, 'two' col, two value
from yourtable
union all
select id, 'three' col, three value
from yourtable
) src
或者你可以使用这样的东西:
SELECT max(data)
FROM
(
SELECT
CASE s.col
WHEN 'one' THEN one
WHEN 'two' THEN two
WHEN 'three' THEN three
END AS DATA
FROM yourtable t
CROSS JOIN
(
SELECT 'one' AS col
UNION ALL SELECT 'two'
UNION ALL SELECT 'three'
) s
) s
试试这个查询
SELECT tempTable.id, tempTable.max(val)
FROM (SELECT id, max(one) AS val
FROM tbl
UNION
SELECT id, max(two) AS val
FROM tbl
UNION
SELECT id, max(three) AS val
FROM tbl
) AS tempTable;
您可以使用case
声明
SELECT
CASE
WHEN one >= two AND one >= three THEN one
WHEN two >= one AND two >= three THEN two
WHEN three >= one AND three >= two THEN three
ELSE one
END AS MaxVal
select max( if( one > two, if( one > three, one, three ), if( two > three, two, three ) )
from Rating