简体   繁体   中英

select min value in same row in sql

I want to select min value of dates in same row of different columns.

eg

column1       column2     column3
2017-01-26  2017-01-28  2017-01-27

in above three columns i would like to select min date ie result of select should be 2017-01-26

Most databases support least() and greatest() :

select least(column1, column2, column3) as min_column,
       greatest(column1, column2, column3) as max_column

In any database, you can use ANSI standard case for the logic:

select (case when column1 >= column2 and column1 >= column3 then column1
             when column2 >= column3 then column2
             else column3
        end) as max_column

(And then similar logic for the min.)

If using SQL Server, you can use this approach:

SELECT (SELECT MIN(columnX) FROM (VALUES(column1), (column2), (column3)) x(columnX))
FROM ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM