Sort by minimum value of two columns

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

    You can use min function in order by clause:

    select * 
    from [table] d
    order by ( select min(q.t) from (
               select d.date1 t union select d.date2) q
             )
    

    You can also use case statement in order by clause but as you know the result of comparing (> and <) any value (null or none null) with null is not true even if you have setted ansi_nulls to off. so for guaranteeing the sort you wanted, you need to handle nulls, as you know in case clause if the result of a when is true then further when statements are not evaluated so you can say:

    select * from [table]
    order by case 
               when date1 is null then date2
               when date2 is null then date1 
               when date1

    Also here are some other solutions if your scenario be different maybe maybe you evaluate the result of comparing multiple columns(or a calculation) inside a separated field and finally order by that calculated field without using any condition inside your order by clause.

提交回复
热议问题