通过使用左连接指定条件来获取空值

时间:2014-08-20 16:42:17

标签: sql sql-server sql-server-2008

表格中有以下数据: -

EMPNO   NAME    DATEFROM                   DATETO
111     xxx   2014-08-03  00:00:00.000    2014-09-05  00:00:00.000
222     yyy   2014-10-03  00:00:00.000    2014-10-05  00:00:00.000

但是当我在下面写下查询:

select empno,name,sum(datediff(day,DATEFROM,DATETO)+1) as holiday 
from leave 
where DATEFROM>='2014-08-01' 
   and DATETO<='2014-08-31' 
   and empno=111 
group by name ,empno

然后我没有得到任何价值..但这个查询我想要低于输出:

 EMPNO  NAME    holiday
  111   xxx      29
8月有31天..

那我该怎么办?

it will only count the day of august(08) month

1 个答案:

答案 0 :(得分:1)

在您的查询中,您指定的DateTo必须为<= 2014-08-31 ...但您的记录中的DateTo值为2014-09-05。所以这是排除它。

我假设你想要所有8月份开始的记录,所以在这两种情况下都需要DateFrom

根据您的更新/评论:

declare @data table (empno int, name varchar(5), datefrom datetime, dateto datetime)
insert into @data
select 111,'xxx','2014-08-03 00:00:00.000','2014-09-05  00:00:00.000'

declare @maxdate datetime, @mindate datetime
set @mindate = '2014-08-01'
set @maxdate = '2014-08-31'

select empno,name,sum(datediff(day,DATEFROM,case when dateto > @maxdate then @maxdate else dateto end)+1) as holiday 
from @data 
where DATEFROM >=@mindate and DATEFROM <=@maxdate and empno=111 group by name ,empno

根据你关于周末的最后一个问题。您需要做的是将日历表交叉加入事件,并省略您不想要的日期。从那里开始,您可以简单地计算剩余的天数,而不是datediff()

declare @data table (empno int, name varchar(5), datefrom datetime, dateto datetime)
insert into @data
select 111,'xxx','2014-08-03 00:00:00.000','2014-09-05  00:00:00.000'

declare @maxdate datetime, @mindate datetime
set @mindate = '2014-08-01'
set @maxdate = '2014-08-31'

;with cal as
(
    select @mindate as dDate, datename(dw, @mindate) as DayWeek
    union all
    select dDate+1, datename(dw, dDate+1) as DayWeek
    from cal
    where dDate+1 <= @maxdate
)

select empno, name, count(*) as holiday
from @data d
cross join cal c
where c.ddate between d.datefrom and d.dateto
and c.dayweek not in ('saturday','sunday')
and DATEFROM >=@mindate and DATEFROM <=@maxdate and empno=111 
group by name ,empno