Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On SQL Server, how to find the MAX or MIN value out of a couple of variables

Tags:

sql-server

max

I just found out that the MAX() function in SQL only works on columns.

Is there a similar function I can use to find the max value out of e.g. these four variables?

SET @return = MAX(@alpha1, @alpha2, @alpha3, @alpha4)

Or do I have to put them in a column first (and thus create a table first...;-( )?

Regards

Lumpi

like image 692
Lumpi Avatar asked Oct 13 '11 08:10

Lumpi


People also ask

How do I get the max of two values in SQL?

The MySQL Solution If you're working with MySQL, you can combine MAX() with the GREATEST() function to get the biggest value from two or more fields. Here's the syntax for GREATEST: GREATEST(value1,value2,...) Given two or more arguments, it returns the largest (maximum-valued) argument.

How can I find the minimum value between two values in SQL Server?

To find the minimum value of a column, use the MIN() aggregate function; it takes as its argument the name of the column for which you want to find the minimum value. If you have not specified any other columns in the SELECT clause, the minimum will be calculated for all records in the table.

How do I SELECT a minimum value from multiple columns in SQL?

you can find a row-wise minimum like this: SELECT C1, C2, C3, ( SELECT MIN(C) FROM (VALUES (C1), (C2), (C3) AS v (C) ) AS MinC FROM T ; Basically you are arranging the values of C1 , C2 , C3 as a column and are applying a normal (column-wise) aggregate function to it to find the minimum.


1 Answers

There is no built-in function in T-SQL for this but you can use following

SELECT @result = MAX(alpha)
FROM   (SELECT @alpha1
        UNION ALL
        SELECT @alpha2
        UNION ALL
        SELECT @alpha3) T(alpha);  

or (SQL Server 2008+)

SELECT @result = MAX(alpha)
FROM  (VALUES(@alpha1),
             (@alpha2),
             (@alpha3)) T(alpha);  
like image 126
Igor Borisenko Avatar answered Sep 22 '22 03:09

Igor Borisenko