Using SQL 2005, is there a way to select the minimum value between 5 columns within one single row of data?
So, if I have a row of data like this:
id num1 num2 num3 num4 num5
1 22 51 4 99 34
Then, how can I get the lowest value using SQL?
You can calculate min using the formula : MIN(a,b) = (a+b)/2 - abs(a-b)/2
probably something like
Most flavours of RDBMS offer LEAST().
Fix your data structure to be normalized so that you don't have to do this complex, performance killing stuff to get the information you need.
TSQL can do it, but it takes a little prep...
First, you need a function:
(it takes a comma-delimeted string of integers, and returns the greatest integer)
And then to create your string of integers (this is the part TSQL isn't very good at):
(in the SELECT)
So to use the function:
The reason I did it like this, instead of the way @mikael did in his answer (wich I +1'd, because it does answer your question), is that this approach will work on any number of fields, not just 5. But honestly, TSQL does have some room to improve here -- they really need a tsql version of plsql's greatest/least functions. Oh well...
You can create a UDF.
And use it like this.
Or you can skip the UDF and use the query directly.