Skip to content
Advertisement

choose minimum date from a record out of multiple columns

Hi I have the following table struct:

Person    Date1             Date2............Daten
------    -----             -----            -----
1         2001-01-01        2002-01-01
2         2003-01-01        2000-01-01

and i want to choose the minimum Date between Date1 and Date(n) (20 dates in my case). So for example it would choose Date1 for Person1 and Date2 for Person2.

obviously i can just use min(Date) if I only have 1 date columns, but I can’t get my logic right in this case.

Thanks very much.

Advertisement

Answer

SELECT person AS the_person
  , LEAST(date1 ,date2, date3, date4, date5, ..., dateN ) AS the_date
FROM the_table ;

Least() should ignore NULLs, if present. (the above works for Postgres)

UPDATE (thanks to @WarrenT) apparently DB2 does not have LEAST(), but it does have MIN() instead (having more than one argument).

SELECT person AS the_person
  , MIN(date1 ,date2, date3, date4, date5, ..., dateN ) AS the_date
FROM the_table ;
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement