如何查找包含NULL的列的最大值并将其视为最大值

时间:2014-06-10 19:25:05

标签: sql sql-server sql-server-2008

我有一个包含日期列的表格,其中包含日期和NULL值。我试图找出一种方法来查找MAX Date,每ID,或者如果有NULL值,则返回NULL

例如:

ID    Date
1     2014-01-01
1     2014-02-01
1     2014-03-01
2     2014-02-01
2     NULL
3     NULL
4     2014-03-01

所以我想要产生的是:

1 = 2014-03-01
2 = NULL
3 = NULL
4 = 2014-03-01

截至目前,我正在使用这样的东西:

NULLIF(MAX(COALESCE(n.[SentDate], '12/16/9997')),'12/16/9997') AS [MaxSentDate]

我99%肯定没有人会把日期12/16/9997,但我想提出一个合适的解决方案,而不是使用像这样的hackish。

4 个答案:

答案 0 :(得分:8)

试试这个:

SELECT [ID]
     , CASE WHEN MAX(CASE WHEN [Date] IS NULL THEN 1 ELSE 0 END) = 0 THEN MAX([Date]) END
FROM YourTable
GROUP BY [ID]

答案 1 :(得分:1)

SELECT ID, [Date]
FROM (
      SELECT ID 
         ,[DATE]
         ,ROW_NUMBER() OVER (PARTITION BY ID ORDER BY CASE WHEN [Date] IS NULL 
                                                           THEN '99991212'
                                                           ELSE [Date] END DESC) RN               
      FROM TABLE_NAME) A
WHERE RN = 1

Working SQL FIDDLE

答案 2 :(得分:1)

如果要返回null:

    SELECT id, max([date]) from #t t1
    WHERE not exists (select 1 from #t t2 where t2.date is null and t1.id = t2.id) 
    GROUP BY id
 UNION ALL
    SELECT id, NULL from #t t1 
    WHERE t1.date IS NULL  
    GROUP BY id ;

答案 3 :(得分:0)

您可以使用COUNT(*) = COUNT([DATE])检查组中是否存在空值(对于组中的所有值,右侧部分返回COUNT,左侧部分仅返回非空值):

SELECT [ID]
     , CASE WHEN COUNT(*) = COUNT([DATE]) THEN MAX([DATE]) ELSE NULL END AS [DATE] 
FROM [TEST_TABLE]
GROUP BY [ID]

Example