Finding MAX/MIN values of multiple columns in a row (Using Cross Apply)
I have been working on finding a solution to find the minimum and maximum values from multiple columns within a row. Contrary to belief, that is not why it took so long to make another post. Regardless, I did not want to simply write a table valued function to return a table of the values from the row as a table to perform the min and max functions. That to me seemed lower performing and maybe not the best usage of table valued functions. So I borrowed a new way from another post I found online. This method uses cross apply to bring the columns together. In a sense, it is a table valued function that returns a table of the values specified from that particular row. So it is applied to each row individually and the Min/Max function is applied at that level. It is a lot less lines, much better performing, and cleaner code writing. Below is my example. Take a look and please enjoy!
SELECT ID, MaxCol, MinCol, Col1, Col2, Col3, Col4, Col5, Col6 FROM MyTable a CROSS APPLY (SELECT MAX(CommonColumn) AS MaxRiskVol, MIN (CommonColumn) AS MinRiskVol FROM (VALUES (Col1), (Col2), (Col3), (Col4), (Col5), (Col6)) B(CommonColumn)) C