-2

How Can I get the max value from few columns for each table row?

ID          Date1      Date2      
----------- ---------- ---------- 
1           2019-01-01 2019-12-29 

result:

ID          MaxDate   
----------- ---------- 
1           2019-12-29 
Michal
  • 9
  • 6

2 Answers2

0

SQL Fiddle

MS SQL Server 2017 Schema Setup:

CREATE TABLE MyTable (ID int,Date1 date,Date2 date)
INSERT INTO MyTable (ID,Date1,Date2) VALUES ('1','2019-01-01','2019-12-29')

Query 1:

SELECT
    ID,CASE
        WHEN Date1 >= Date2   THEN Date1
        WHEN Date2 >= Date1 THEN Date2
ELSE   Date1
    END AS MaxDate

    FROM MyTable

Results:

| ID |    MaxDate |
|----|------------|
|  1 | 2019-12-29 |
Amira Bedhiafi
  • 8,088
  • 6
  • 24
  • 60
0
select ID,(select max(d) from (select Date1 d uninon select Date2 d) as t) as MaxDate
from MyTable
Michal
  • 9
  • 6
  • 5
    While this answer may be correct. Code only answers are rarely helpful. Please comment your code and provide an explanation for how this code solves the problem. – RyanNerd Dec 25 '19 at 11:50