如何在SQL中使用带有datetime字段的Select Case

时间:2014-03-22 06:54:21

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

我有一个表utblAdvertise,其中一个字段是PublishedDate,其中包含类似这样的日期时间数据

      PublishedDate
     2014-03-21 15:07:22.173
     2014-02-11 15:05:22.223 
     2014-03-21 15:15:22.673
     2014-01-01 15:15:22.272
     2014-02-11 15:15:22.173
     2014-03-20 15:15:22.372
     2014-03-26 15:15:22.393
     2014-02-25 15:15:22.273

我希望时间仅在发布日期在24 hours之间的时候,例如。 5 Hours ago, 15 Hours ago etc.否则我想显示日期,例如。 11-Feb-2014我已经尝试了一段时间,我的查询如下

       Select PublishedDate,RIGHT(CONVERT(VARCHAR, PublishedDate, 100),7) as Time From CLF.utblAdvertise 

,其结果时间为3:09PM, 11:27AM

我希望输出为

     3 hours ago -- Incase in between 24 hours
     12-Feb-2014 -- incase in not between 24 hours

任何帮助肯定都会受到欢迎。

1 个答案:

答案 0 :(得分:0)

SELECT 
  CASE WHEN DATEDIFF(HOUR, PublishedDate, GETDATE()) < 24 THEN 
    CASE DATEDIFF(HOUR, PublishedDate, GETDATE()) 
    WHEN 1 THEN CONVERT(VARCHAR, DATEDIFF(HOUR, PublishedDate, GETDATE())) + ' hour ago'
    ELSE CONVERT(VARCHAR, DATEDIFF(HOUR, PublishedDate, GETDATE())) + ' hours ago'
    END
  ELSE REPLACE(CONVERT(VARCHAR, PublishedDate, 6), ' ', '-')
  END
FROM Something