5

我有一张如下表

ID   Date  
1    Null  
1    Null  
1    Null  
1    02/02/2012  
1    02/03/2012  
1    02/04/2012  
1    02/05/2012  

我想从上表中取一个最小日期,结果应该是Null

我试图写

select min(date), Id from Table group by ID

然后结果是02/02/2012,但我想要Null

除了下面的方法,还有其他方法可以从上表中提取 Null 值吗?

select top 1 date, ID from table order by date asc
4

4 回答 4

5

假设您的 dbms 是 SQL-Server。

如果您想分组id但无论如何选择所有字段,您可以使用ctewithROW_NUMBER函数:

WITH cte AS(
  SELECT x.*
  , RN=ROW_NUMBER()OVER(Partition By id Order By date)
  FROM Table x
)
SELECT * FROM cte 
WHERE RN=1

http://sqlfiddle.com/#!3/cc2a4/7

于 2012-06-15T15:01:43.790 回答
3

默认情况下,函数 MAX 和 MIN 在评估数据时不计算 NULL。

以这种方式尝试,应该可以解决问题:

SELECT 
CASE WHEN MIN(COALESCE(Date, '19001231')) = '19001231' THEN NULL ELSE MIN(Date) END AS Date,
Id 
FROM X 
group by ID
于 2012-06-15T14:56:59.743 回答
0

我想他们中的一些人已经给出了答案。但最终结果与以下查询一起使用

SELECT CASE WHEN   MIN(coalesce(date, '1900-01-01')) = '1900-01-01' THEN NULL ELSE MIN(date) END AS Date, ID
FROM table
GROUP BY ID
于 2012-06-15T15:10:00.827 回答
0

You can also do a simple check for 'NULL'. I didn't return an "ID" in the example since the "ID" seems meaningless in the example schema/query given.

    IF (EXISTS(SELECT TOP 1 * FROM x WHERE date IS NULL)) SELECT NULL AS MinDate
    ELSE SELECT MIN(date) AS MinDate FROM x;

http://sqlfiddle.com/#!3/d5fca/11

于 2012-06-15T21:20:58.297 回答