Sort by minimum value of two columns

后端 未结 13 1211
暖寄归人
暖寄归人 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:03

    Use a CASE expression in the ORDER BY:

     ORDER BY case when date1 < date2 then date1 else date2 end
    

    Edit:

    If null values need to be considered, add coalesce():

     ORDER BY case when date1 < date2 then date1 else coalesce(date2,date1) end
    

    Explanation:

    If date1 < date2 then order by date1. (Both dates are non null here.) Works just like before.

    Else use COALESCE() to order by date2 (when date2 is not null), or date1 (when date2 is null), or by null (if both dates are null.)

提交回复
热议问题