Get the minimum value between several columns

后端 未结 4 567
遇见更好的自我
遇见更好的自我 2020-12-20 19:35

I\'m using SQL Server 2008;

Suppose I have a table \'X\' with columns \'Date1\', \'Date2\', \'Dateblah\', all of type DateTime.

I want to select the min valu

4条回答
  •  佛祖请我去吃肉
    2020-12-20 19:59

    There is no built in function to return the min/max of two (or more) columns. You could implement your own scalar function to do this.

    In SQL Server 2005+ you could use UNPIVOT to turn the columns into rows and then use the MIN function:

    CREATE TABLE [X]
    (
        [ID] INT,
        [Date1] DATETIME,
        [Date2] DATETIME,
        [Date3] DATETIME
    )
    
    INSERT  [X]
    VALUES  (0, '09/29/2011', '09/20/2011', '09/01/2011'),
            (1, '01/01/2011', '01/05/2011', '03/03/2010')
    
    
    SELECT [ID], MIN([Date]) AS [MinDate]
    FROM [X]
    UNPIVOT (
        [Date] FOR d IN
            ([Date1]
            ,[Date2]
            ,[Date3])
    ) unpvt
    GROUP BY [ID]
    

提交回复
热议问题