Sort by minimum value of two columns

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

    I think when you want to sort on both fields of date1 and date2, you should have both of them in the ORDER BY part, like this:

    SELECT *
    FROM aTable
    ORDER BY 
        CASE WHEN date1 < date2 THEN date1 
        ELSE date2 END, 
        CASE WHEN date1 < date2 THEN date2 
        ELSE date1 END
    

    Result can be like this:

    date1      | date2      
    -----------+------------
    2015-04-25 | 2015-04-21
    2015-04-26 | 2015-04-21
    2015-04-25 | 2015-04-22
    2015-04-22 | 2015-04-26
    

    To have a prefect result with Null values use:

    SELECT *
    FROM aTable
    ORDER BY 
        CASE 
            WHEN date1 IS NULL THEN NULL
            WHEN date1 < date2 THEN date1 
        ELSE date2 END 
        ,CASE 
            WHEN date2 IS NULL THEN date1
            WHEN date1 IS NULL THEN date2
            WHEN date1 < date2 THEN date2 
        ELSE date1 END
    

    Results will be like this:

    date1      | date2      
    -----------+------------
    NULL       | NULL
    NULL       | 2015-04-22
    2015-04-26 | NULL
    2015-04-25 | 2015-04-21
    2015-04-26 | 2015-04-21
    2015-04-25 | 2015-04-22
    

提交回复
热议问题