Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

SQL MAX of multiple columns?

How do you return 1 value per row of the max of several columns:

TableName
[Number, Date1, Date2, Date3, Cost]


I need to return something like this:

[Number, Most_Recent_Date, Cost]

Query?
by

3 Answers

akshay1995
Well, you can use the CASE statement:

SELECT
CASE
WHEN Date1 >= Date2 AND Date1 >= Date3 THEN Date1
WHEN Date2 >= Date1 AND Date2 >= Date3 THEN Date2
WHEN Date3 >= Date1 AND Date3 >= Date2 THEN Date3
ELSE Date1
END AS MostRecentDate
sandhya6gczb
Here is another nice solution for the Max functionality using T-SQL and SQL Server

SELECT [Other Fields],
(SELECT Max(v)
FROM (VALUES (date1), (date2), (date3),...) AS value(v)) as [MaxDate]
FROM [YourTableName]
RoliMishra
If you're using MySQL, you can use

SELECT GREATEST(col1, col2 ...) FROM table

Login / Signup to Answer the Question.