计算DIFFDATE超过指定值 - 步骤3

时间:2009-04-01 14:14:56

标签: sql

与昨天提出的问题一样,我还有另一个“数不清”的困境。现在我需要提取满足以下参数的条件条目的计数:

  1. ConditionLevelEntryID = 189
  2. CheckoffDate是>来自ConditionEntryDateTime
  3. 的14天
  4. CheckoffDate IS NULL且ConditionEntryDateTime> 14天
  5. 我尝试过查询(如下),但不起作用。返回的错误低于查询。请帮我改进查询以获得准确的计数。提前谢谢。

    select Count(*)
    from conditionentrytable c
    where conditionlevelentryid=189
        and 
        ((c.checkoffdate IS NULL 
        and 
        convert(varchar(12),DATEADD(day,14,c.conditionentrydatetime)))
        or 
        DATEDIFF(dd,c.checkoffdate,c.conditionentrydatetime)>14)
    
      

    服务器:消息170,级别15,状态1,   第7行第7行:附近的语法不正确   ')'

2 个答案:

答案 0 :(得分:2)

试试这个:

SELECT  COUNT(*)
FROM    conditionentrytable c
WHERE   conditionlevelentryid=189
        AND DATEDIFF(dd, COALESCE(c.checkoffdate, GETDATE()),c.conditionentrydatetime) > 14

,甚至更好:

SELECT  COUNT(*)
FROM    conditionentrytable c
WHERE   conditionlevelentryid=189
        AND c.conditionentrydatetime > COALESCE(c.checkoffdate, GETDATE()) - 14

后一个查询将使用(conditionlevelentryid, conditionentrydatetime)上的复合索引(如果有),这很可能会极大地提高查询性能。

答案 1 :(得分:1)

我自己有点生锈,但在IS NULL表达式中转换的conditionentrydatetime没有做任何事情。

怎么样?

select Count(*)
from conditionentrytable c
where conditionlevelentryid=189
    and 
    ((c.checkoffdate IS NULL 
    and 
    DATEDIFF(dd,getdate(),c.conditionentrydatetime)>14)
    or 
    DATEDIFF(dd,c.checkoffdate,c.conditionentrydatetime)>14))