Sort by minimum value of two columns

后端 未结 13 1215
暖寄归人
暖寄归人 2021-02-03 17:13

I use SQL Server 2008 R2.

I need to sort a table by the minimal value of two columns.

The table looks like this:

ID: integer; 
Date         


        
13条回答
  •  日久生厌
    2021-02-03 18:00

    NOT NULL columns. You need to add CASE statement into ORDER BY clause in following:

    SELECT Id, Date1, Date2
    FROM YourTable
    ORDER BY CASE 
               WHEN Date1 < Date2 THEN Date1 
               ELSE Date2 
             END 
    

    NULLABLE columns. As Zohar Peled wrote in comments if columns are nullable you could use ISNULL (but better to use COALESCE instead of ISNULL, because It's ANSI SQL standard) in following:

    SELECT Id, Date1, Date2
    FROM YourTable
    ORDER BY CASE 
               WHEN COALESCE(Date1, '1753-01-01') < COALESCE(Date2, '1753-01-01') THEN Date1 
               ELSE Date2 
             END
    

    You can read about ANSI standard dateformat 1753-01-01 here.

提交回复
热议问题