如何将默认值分配给聚合函数中的日期?

时间:2010-12-21 17:16:11

标签: sql sql-server-2005

select isnull(min(date_tested),'01-01-2010') from test_date where date_tested>=@startdate and enddate<=@enddate 

我有时得到这个输出 -

datetested
__________

我想要 -

datetested
01-01-2010

所以这不起作用...我的意思是在日期不存在的情况下它返回空白..我希望在它返回时返回一个默认值我猜空白....因为我猜date_tested不是null否则它将具有asigned的值。如果它为null,我可以为它指定默认值吗?

5 个答案:

答案 0 :(得分:0)

请改为尝试:

从test_date组中选择min(isnull(date_tested,'01 -01-2010'))by date_tested

在聚合中使用isnull和case语句可以获得很多权力

答案 1 :(得分:0)

试试这个

select coalesce(date_tested,'01-01-2010') from test_date group by date_tested

答案 2 :(得分:0)

为什么要按聚合函数中使用的列进行分组?如果有{X}值满足WHERE中的条件,则会获得X行。但如果它真的是你想要的,你可以使用

SELECT 
ISNULL((SELECT MIN(date_tested) 
FROM test_date 
WHERE date_tested>=@startdate and enddate<=@enddate  
group by date_tested),'01-01-2010') as [datetested];

答案 3 :(得分:0)

好吧,我不明白你是否想要MIN date_tested,或者你想要date_tested的所有可能值,因为你在date_tested上使用MIN而你是GROUPING BY date_tested。如果您想要MIN值,那么您可以执行以下操作:

SELECT MIN(ISNULL(date_tested,'01-01-2010'))
FROM test_date
WHERE date_tested>=@startdate and enddate<=@enddate 

你必须要小心,因为如果它为null,你要为date_tested赋值。如果你想要date_tested的所有可能值,那么你可以这样做:

SELECT ISNULL(date_tested,'01-01-2010')
FROM test_date
WHERE date_tested>=@startdate and enddate<=@enddate 
GROUP BY ISNULL(date_tested,'01-01-2010')

答案 4 :(得分:0)

尝试使用您的开始日期参数作为默认值...

select isnull(min(date_tested),@startdate)
from test_date 
where date_tested>=@startdate 
and enddate<=@enddate
相关问题