Link to home
Start Free TrialLog in
Avatar of dcmorrell
dcmorrell

asked on

SQL: select max value... In row, across columns

Example:
col1      col2      col3      col4      col5      col6
1      0      0      3      0      2
1      1      2      0      0      2
1      2      2      4      3      1

I want to be able to create a column that takes the highest value amonst all these fields on their respective row, something like:
" select highest(col1, col2, col3, col4, col5, col6) as highestValue "

Anything out there like that? Keep in mind I actually have 13 columns.
   
Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg image

you will need a stored function for that, this version with 5 arguments:

as functions don't allow optional arguments, I would create a function with 15 arguments, and pass in your example 2 null values at the end.
create function dbo.Highest_05(@val1 sql_variant, @val2 sql_Variant, @val3 sql_variant, @val4 sql_variant, @val5 sql_Variant) returns sql_variant
as
begin
  declare @t table(data sql_Variant)
  declare @res sql_Variant
  insert into @t values(@val1)
  insert into @t values(@val2)
  insert into @t values(@val3)
  insert into @t values(@val4)
  insert into @t values(@val5)
  select @res = max(data) from @t
  return @res
end
go
select dbo.Highest_05(1,2,3,'A', null)
go
drop function dbo.Highest_05

Open in new window

try this create a function and use it as follows, i used 4 params you can expand it

Create FUNCTION [dbo].[Greatest]
(
@val1 int,
@val2 int,
@val3 int,
@val4 int
)
RETURNS int
AS
BEGIN
      -- Declare the return variable here
      DECLARE @ResultVar int

      -- Add the T-SQL statements to compute the return value here
      SELECT @ResultVar = max(MyVal) From
            (Select @val1 MyVal
            union Select @val2
            union Select @val3
            union Select @val4) A

      -- Return the result of the function
      RETURN @ResultVar

END


Select Col1,Col2,Col3,Col4,
dbo.Greatest(Col1,Col2,Col3,Col4)
from dbo.TestTab
select max(col1),max(col2),max(col3),max(col4),max(col5),max(col6) from yourtablename
 
must help.
sorry I misunderstood your need
Avatar of vinurajr
vinurajr

ASKER CERTIFIED SOLUTION
Avatar of Scott Pletcher
Scott Pletcher
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Functions have fairly significant overhead anyway, so should always be written as efficiently as possible :-) .
Avatar of dcmorrell

ASKER

Works perfectly, thank you!