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.
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 ).
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.
The MAX() function returns the largest value of the selected column.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With