SQL Server条件用例无法按预期工作

时间:2018-07-25 01:20:21

标签: sql-server

当条件是状态名称在确切的到期日显示为关闭时,我希望我的SQL显示过期的计数,然后将计数设置为1。例如,在到期日,状态名称仅变为关闭。

select 
    category, COUNT(overdue) as overdue2 
from 
    (select 
         Category, due,
         case when DATEDIFF(day, Due, SYSDATETIME()) = 0 then 1   
              else 0 
         end as overdue 
     from 
         FeedbackDetail 
     where 
         StatusName = 'Closed' and  
         FeedbackDatetime >= '2018-01-01') a 
Group by 
    Category

我的预期结果是显示在确切的截止日期时间关闭状态名称的计数。

对此有任何想法吗?

2 个答案:

答案 0 :(得分:1)

COUNT个聚合函数对现有(非空)值进行计数,因此它将同时计数0和1。由于您没有发布整个查询,因此我们不知道a1是什么,唯一的解决方案可以提出的是:

使用SUM代替COUNT

答案 1 :(得分:0)

You can modify the query like given below for better performance and working.

DECLARE @currentDateTime DATETIME = GETDATE()
select 
    category, SUM(overdue) as overdue2 
from 
    (select 
         Category, 
         case when DATEDIFF(day, Due, @currentDateTime) = 0 then 1   
              else 0 
         end as overdue 
     from 
         FeedbackDetail 
     where 
         StatusName = 'Closed' and  
         FeedbackDatetime >= '2018-01-01') a 
Group by 
    Category