This article is half-done without your Comment! *** Please share your thoughts via Comment ***
In this post, I am sharing a T-SQL Script to find the MAX value from Multiple columns in SQL Server.
For example:
In our table, we have three different date columns and need to find the one max value out of this three columns.
I worked around this and tested different solution for the performance. I am sharing one of the best solutions here.
I have tested different solutions like UNPIVOT, UNION, InnerQuery.
Note: Below T-SQL script solution work with the only same type of columns.
Let’s First, create sample table and data:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
CREATE TABLE tbl_FindMAX ( ID INT IDENTITY(1,1) PRIMARY KEY ,Name NVARCHAR(255) ,UpdatedDate1 DATETIME ,UpdatedDate2 DATETIME ,UpdatedDate3 DATETIME ) INSERT INTO tbl_FindMAX(Name, UpdatedDate1, UpdatedDate2, UpdatedDate3 ) VALUES('Anvesh', '2015-08-08','2015-10-10', '2015-11-08'), ('Neevan', '2015-08-26','2010-10-08', '2015-05-16'), ('Akash', '2014-02-26','2014-02-16', '2015-08-16') |
T-SQL Script to Find MAX Value from three different Date Columns:
1 2 3 4 5 6 |
SELECT ID, (SELECT MAX(LastUpdateDate) FROM (VALUES (UpdatedDate1),(UpdatedDate2),(UpdatedDate3)) AS UpdateDate(LastUpdateDate)) AS LastUpdateDate FROM tbl_FindMAX |
The Result: