How to get the maximum value in each row

Lylyy 380 Reputation points
2023-09-18T07:27:08.71+00:00

I want to calculate the max value in each row. I have tried with Max(), and not worked.

Sample like this:

User's image

SQL Server | Other
0 comments No comments
{count} votes

Accepted answer
  1. LiHongMSFT-4306 31,566 Reputation points
    2023-09-18T07:36:10.3433333+00:00

    Hi @Lylyy

    Please try this query:

    DECLARE @tbl TABLE(val1 INT,val2 INT,val3 INT); 
    INSERT @tbl VALUES(5,3,8),(2,9,4); 
    
    SELECT *,(SELECT MAX(val) FROM (VALUES (val1),(val2),(val3)) AS value(val)) AS MaxVal  
    FROM @tbl;  
    

    Best regards,

    Cosmog Hong

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Erland Sommarskog 121.4K Reputation points MVP Volunteer Moderator
    2023-09-18T20:59:02.31+00:00

    If you are on SQL 2022 or Azure SQL Database, you can use greatest:

    SELECT greatest(val1, val2, val3)
    FROM tbl
    
    
    

    If you are on old versions, Cosmog's query is the best solution.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.