Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - Select the largest value within a row

Tags:

sql

max

ssms

I seem to be stuck on this and can't find a solution having had a look around.

I have an SQL table who's first row looks something like this:

Name   Val1   Val2   Val3
John   1000   2000   3000

What I need to do is Select the largest value within this row i.e. 3000

Obviously if these values were in a column rather than row you could just use SELECT MAX(column) FROM table to get the largest value in the column. Is there an equivalent of this for finding the max value in a row?

I have also had a look at the uses of PIVOT and UNPIVOT but I don't think they are useful to me here..

The only way I have been able to do it is to create a temp table and insert each value into a single column like so:

CREATE TABLE #temp (colvals float)
     INSERT INTO #temp (colvals)
          SELECT Val1 FROM table WHERE ID=1
         UNION
          SELECT Val2 FROM table WHERE ID=1
         UNION
          SELECT Val3 FROM table WHERE ID=1
--------------------------------------------
SELECT MAX(colvals) FROM #temp
--------------------------------------------
DROP TABLE #temp

However I feel this is rather slow especially as my table has a lot more columns than the snippet I have shown above.

Any ideas?

Thanks in advance.

like image 233
Johnathan Avatar asked Dec 02 '15 09:12

Johnathan


People also ask

How do you find the highest value in a row in SQL?

To find the maximum value of a column, use the MAX() aggregate function; it takes a column name or an expression to find the maximum value. In our example, the subquery returns the highest number in the column grade (subquery: SELECT MAX(grade) FROM student ).

How do you SELECT a row with maximum value?

MySQL select the row with maximum value in a column : MAX() function. This section will help us learn how to get the maximum value for a column and get the record details corresponding to it. Let us start by creating a table sales_details followed by inserting some records to it.

How do you SELECT the highest value in SQL?

The MAX() function returns the largest value of the selected column.


1 Answers

You can build a reference table for columns by APPLY and use native MAX()

-- Sample Data
declare @data table (Name varchar(10), Val1 int, Val2 int, Val3 int, Val4 int, Val5 int, Val6 int)
insert @data values 
    ('John', 1000, 2000, 3000, 4000, 5000, 6000),
    ('Mary', 1, 2, 3, 4, 5, 6)


select Name, MaxValue from 
    @data 
    cross apply 
    (
        select max(value) as MaxValue 
        from 
            (values
                (Val1),(Val2),(Val3),(Val4),(Val5),(Val6) -- Append here
            ) t(value)
    ) result

SQL Fiddle

like image 100
Eric Avatar answered Oct 15 '22 04:10

Eric