I had a situation last week where I needed to find the MIN() and MAX() values of some data. Normally this would be pretty straightforward, but the problem was I needed to identify the MIN() and MAX() values amongst multiple columns. So today I bring you a SQL tip using APPLY.
Looking at sys.procedures we can see I have a create_date and a modify_date column for each record. What if we needed to return the MIN() or MAX() value from those 2 (or more) columns?
SELECT [Name] ,create_date ,modify_date FROM sys.procedures AS p WHERE p.[name] = 'ChangePassword';
We can actually do this using CROSS APPLY.
SELECT [Name] ,p.create_date ,p.modify_date ,MIN(xa.DateColumn) AS Least ,MAX(xa.DateColumn) AS Greatest FROM sys.procedures AS p CROSS APPLY ( VALUES (p.create_date) ,(p.modify_date) ) AS xa(DateColumn) WHERE p.[name] = 'ChangePassword' GROUP BY p.[name] ,p.create_date ,p.modify_date;
Using the APPLY operator we can supply a list of values, and that list of values can actually come from tables or views that were used earlier on. In my example, I’m querying from sys.procedures, and to make this work I’m using the columns create_date and modify_date and shoving them into a VALUES() clause which will essentially become a dataset that can be evaluated.
Now I have a dataset named [x] that contains one column [DateColumn]. With this new dataset I’ve created, I can now use MIN() and MAX() to evaluate the values within. This will allow me to get the LEAST and GREATEST values from the CROSS APPLY.
As always, thank you for reading!
One thought on “Finding the Least and Greatest value over multiple columns.”