如何获取比较SQL中两个日期之间的天数的记录数?

时间:2017-01-03 05:46:00

标签: sql sql-server

declare @UserId varchar(30);
declare @StartDate datetime;
declare @EndDate datetime;

set @UserId = 'E2';
set @StartDate = '2016-12-01';
set @EndDate = '2016-12-14';

select 
    COUNT((dueDate < finishDate) or finishDate = nul) as exceedTasks,   
    COUNT(taskID) as totalTasks 
from 
    Task
where 
    empId = @UserId 
    and startDate >= @StartDate 
    and dueDate <= @EndDate 

我希望获得超过count的{​​{1}}个任务。但此查询存在语法错误。

1 个答案:

答案 0 :(得分:1)

可能是因为你写了nul而不是null。 你可以试试这个

declare @UserId varchar(30);
declare @StartDate datetime;
declare @EndDate datetime;

set @UserId = 'E2';
 set @StartDate = '2016-12-01';
   set @EndDate = '2016-12-14';

  select 
 COUNT((dueDate < finishDate) or finishDate = null) as exceedTasks,   
     COUNT(taskID) as totalTasks 
   from 
    Task
      where 
empId = @UserId 
and startDate >= @StartDate 
and dueDate <= @EndDate 

试试这个

 declare @UserId varchar(30);
declare @StartDate datetime;
 declare @EndDate datetime;

set @UserId = 'E2';
set @StartDate = '2016-12-01';
 set @EndDate = '2016-12-14';

 select 
 COUNT(CASE WHEN dueDate < finishDate THEN dueDate WHEN finishDate = null THEN dueDate END ) as exceedTasks,   
 COUNT(taskID) as totalTasks 
   from 
   Task
  where 
empId = @UserId 
and startDate >= @StartDate 
and dueDate <= @EndDate