SQL: Find the Max value from a list of values

SQL MAX function will return the max value for a given column of a table.

What if you want to get the max value of multiple date fields for a given row?

The answer is to use virtual/derived table/column.

 

SELECT [col1, col2, etc]
(SELECT Max(vCol1)
FROM (VALUES (date1), (date2), (date3), ...) AS vTable(vCol1)) as [MaxDate],
FROM [mytable]

credit to Sven for the solution idea.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s