Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save sbealer/a1041cc3cdc61dbe46b5 to your computer and use it in GitHub Desktop.
Save sbealer/a1041cc3cdc61dbe46b5 to your computer and use it in GitHub Desktop.
Get max row from multiple columns using VALUES clause
/* This method has the best performance over other methods normally used (union all, etc)*/
SELECT TOP 50
INV.PONUMBER
,INV.KEYINDATE
,INV.PAIDDATE
,INV.DATE
,
(SELECT
MAX(LASTUPDATEDATE)
FROM (VALUES (INV.KEYINDATE), (INV.PAIDDATE), (INV.DATE)) AS UPDATEDATE (LASTUPDATEDATE))
AS THIS_IS_THE_MAX_DATE_FROM_THE_3_COLUMNS
FROM OMC..INVOICES AS INV;
/*Other cool stuff you can do with the VALUES clause*/
SELECT
*
FROM (VALUES ('Recommendation', 'Other'), ('Review', 'Marketing'), ('Internet', 'Promotion'))
AS SOURCE (NEWNAME, NEWREASONTYPE);
Taken from this article: https://www.mssqltips.com/sqlservertip/4067/find-max-value-from-multiple-columns-in-a-sql-server-table/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment