Sort by minimum value of two columns

后端 未结 13 1486
暖寄归人
暖寄归人 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 17:47

    I would order the rows by this rules:

    1. when both null
    2. when date1 is null
    3. when date 2 is null
    4. min(date1, date2)

    To do this a nested case will be simple and efficient (unless the table is very large) according to this post.

    SELECT ID, Date1, Date2
    FROM YourTable
    ORDER BY 
    CASE 
      WHEN Date1 IS NULL AND Date2 IS NULL THEN 0
      WHEN Date1 IS NULL THEN 1
      WHEN Date2 IS NULL THEN 2
      ELSE 3 END,
    CASE 
      WHEN Date1 < Date2 THEN Date1
      ELSE Date2
    END
    

提交回复
热议问题