12

我有表:

评分:

id | one | two | three
1  | 12  | 3   | 7
2  | 11  | 30  | 3
3  | 8   | 14  | 4

如何从这些字段(一、二、三)中获取 SQL MAX 值?对于此示例,这是30

4

7 回答 7

20

在 MySQL 中,您可以使用GREATEST函数:

SELECT  MAX(GREATEST(one, two, three))
FROM    T;

SQL Fiddle 示例

于 2013-03-01T11:57:27.293 回答
6
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
于 2013-03-01T11:58:46.227 回答
4
select GREATEST(max(one), max(two), max(three)) as maximum 
from table;
于 2013-03-01T11:59:22.860 回答
3

您可以像这样取消透视数据:

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

请参阅SQL Fiddle with Demo

或者你可以使用这样的东西:

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

请参阅带有演示的 SQL Fiddle

于 2013-03-01T11:57:16.437 回答
3

试试这个查询

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;
于 2013-03-01T11:57:59.067 回答
1

您可以使用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
于 2013-03-01T12:00:16.173 回答
1
select max( if( one > two, if( one > three, one, three ), if( two > three, two, three ) )
  from Rating
于 2013-03-01T11:58:42.480 回答