Choosing MAX() of Multiple Columns, With Names

If you need the max value from among multiple columns in a single row, but you also need to know which column contained that max value, try the following. It’s easily modified to provide MIN values, or additional columns.

This example returns the max date from among three date columns in one row.

WITH CTE (Date_Column, Selected_Date) AS (

	SELECT 'Contact_Date' AS Date_Column, Contact_Date
		FROM a_Ticket_Action WHERE Ticket_Action_SKey = @Ticket_SKey UNION ALL
	SELECT 'Maint_Date' AS Date_Column, Maint_Date
		FROM a_Ticket_Action WHERE Ticket_Action_SKey = @Ticket_SKey UNION ALL
	SELECT 'Create_Date' AS Date_Column, Create_Date
		FROM a_Ticket_Action WHERE Ticket_Action_SKey = @Ticket_SKey
)
SELECT TOP 1 Date_Column, max(Selected_Date) FROM CTE
GROUP BY Date_Column
ORDER BY MAX(Selected_Date) DESC

You need to supply a value for ticket_skey in this example.

Advertisements

About combatdba

I'm a production DBA at a terabyte-class SQL Server Shop
This entry was posted in Procedures. Bookmark the permalink.

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