Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Three columns - get MAX with SQL

Tags:

sql

php

mysql

I have table:

Rating:

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

How can i get with SQL MAX values from these fields (one, two, three)? For this example this is 30.

like image 966
Mike Boostger Avatar asked Mar 01 '13 11:03

Mike Boostger


People also ask

How do I get the maximum number of multiple columns in SQL?

The MySQL Solution If you're working with MySQL, you can combine MAX() with the GREATEST() function to get the biggest value from two or more fields.

How do I SELECT 3 columns in SQL?

In the real world, you will often want to select multiple columns. Luckily, SQL makes this really easy. To select multiple columns from a table, simply separate the column names with commas!

Can I GROUP BY 3 columns in SQL?

Yes, it is possible to use MySQL GROUP BY clause with multiple columns just as we can use MySQL DISTINCT clause.


2 Answers

In MySQL you can use the GREATEST Function:

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

Example on SQL Fiddle

like image 173
GarethD Avatar answered Sep 24 '22 11:09

GarethD


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
like image 41
Oto Shavadze Avatar answered Sep 22 '22 11:09

Oto Shavadze