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?
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?
here is a good solution:
Based on the ScottPletcher's solution from http://www.experts-exchange.com/Microsoft/Development/MS-SQL-Server/Q_24204894.html I’ve created a set of functions (e.g. GetMaxOfDates3 , GetMaxOfDates13 )to find max of up to 13 Date values using UNION ALL. See T-SQL function to Get Maximum of values from the same row However I haven't considered UNPIVOT solution at the time of writing these functions
Problem: choose the minimum rate value given to an entity Requirements: Agency rates can be null
Inspired by this answer from Nat
Another way to use CASE WHEN
There are 3 more methods where
UNPIVOT
(1) is the fastest by far, followed by Simulated Unpivot (3) which is much slower than (1) but still faster than (2)Solution 1 (
UNPIVOT
)Solution 2 (Sub query per row)
Solution 3 (Simulated
UNPIVOT
)This is slightly easier to write out and skips evaluation steps as the case statement is evaluated in order.