SQL查询 - 用文本IF日期替换NULL超过30天

时间:2015-04-23 16:07:43

标签: sql-server tsql sql-server-2008-r2

版本:SQL Server 2008 R2

我目前正在接收如下输出:

f_ID     f_lastonline         f_reasonforoffline
===============================================================
1        01/01/2015 12:00:00  ISP Down
2        02/02/2015 12:00:00  Hardware Failure
3        03/03/2015 12:00:00  NULL
4        04/23/2015 12:00:00  NULL

我可以使用

将默认值替换为NULL值
SELECT
  f_ID,
  f_lastonline,
  ISNULL(f_reasonforoffline, 'Likely Turned Off') AS f_reasonforoffline

此查询语法将返回如下输出:

f_ID     f_lastonline         f_reasonforoffline
===============================================================
1        01/01/2015 12:00:00  ISP Down
2        02/02/2015 12:00:00  Hardware Failure
3        03/03/2015 12:00:00  Likely Turned Off
4        04/23/2015 12:00:00  Likely Turned Off

但是,如果“f_lastonline”日期早于30天,我只想将文字更改为“可能已关闭”。

要在代码中解释(但请注意,这在语法上是不正确的),这是我希望实现的:

ISNULL(IF f_lastonline <= DATEADD(dd,DATEDIFF(dd,0,GETDATE()),-30) THEN f_reasonforoffline, 'Likely Turned Off' ELSE f_reasonforoffline, '') AS f_reasonforoffline,

然后,最终所需的输出将是以下情况:2015年3月3日(超过30天)的NULL'f_reasonforoffline'将更改为“可能关闭”和NULL“f_reasonforoffline”值从2015年4月23日起,将简单地更改为''(不为空,只是空白)。

f_ID     f_lastonline         f_reasonforoffline
===============================================================
1        01/01/2015 12:00:00  ISP Down
2        02/02/2015 12:00:00  Hardware Failure
3        03/03/2015 12:00:00  Likely Turned Off
4        04/23/2015 12:00:00  

*注意:这样做的原因是我不必解释“NULL”对于查看报告的人的意义。

提前致谢, Beems

1 个答案:

答案 0 :(得分:2)

SELECT
  f_ID,
  f_lastonline,
  CASE 
    WHEN f_lastonline < DATEADD(DD,-30,GETDATE()) 
    THEN ISNULL(f_reasonforoffline, 'Likely Turned Off') 
    ELSE f_reasonforoffline 
  END AS f_reasonforoffline