Sort by minimum value of two columns

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

    Code for max

    I'm using CROSS APPLY, I am not sure about the performance, But CROSS APPLY often has a better performance in my experience.

    CREATE TABLE #Test (ID INT, Date1 DATETIME, Date2 DATETIME)
    INSERT INTO #Test SELECT 1, NULL, '1/1/1';INSERT INTO #Test SELECT 2, NULL, NULL;INSERT INTO #Test SELECT 3, '2/2/2', '3/3/1';INSERT INTO #Test SELECT 4, '3/3/3', '11/1/1'
    
    SELECT t.ID, Date1, Date2, MinDate
    FROM #TEST t
        CROSS APPLY (SELECT MIN(d) MinDate FROM (VALUES (Date1), (Date2)) AS a(d)) md
    ORDER BY MinDate
    
    DROP TABLE #Test
    

提交回复
热议问题