Sort by minimum value of two columns

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

    There's an another option. You can calculate the result column by needed logic and cover the select by external one with ordering by your column. In this case the code will be the following:

    select ID, x.Date1, x.Date2
    from
    (
        select
            ID,
            Date1,
            Date2, 
            SortColumn = case when Date1 < Date2 then Date1 else Date2 end
        from YourTable
    ) x
    order by x.SortColumn
    

    The benefit of this solution is that you can add necessary filtering queries (in the inner select) and still the indexes will be useful.

提交回复
热议问题