如果我有具有以下结构的假期表:
emp_num start_date end_date
234 8-2-2015 8-5-2015
234 6-28-2015 7-1-2015
234 8-29-2015 9-2-2015
115 6-7-2015 6-7-2015
115 8-7-2015 8-10-2015
考虑日期格式为:m/dd/yyyy
我怎样才能获得每个员工在特定月份的假期总和。
假设我想在8Aug-2015
获得假期
我想要这样的结果
emp_num sum
234 7
115 4
7
= 8-2-2015 和 8-5-2015
之间的所有日期 加上
8-29 之间的所有日期-2015 和 8-31-2015
月底
最佳答案
希望这对你有帮助
declare @temp table
(emp_num int, startdate date, enddate date)
insert into @temp values (234,'8-2-2015','8-5-2015')
insert into @temp values (234,'6-28-2015','7-1-2015')
insert into @temp values (234,'8-29-2015','9-2-2015')
insert into @temp values (115,'6-7-2015','6-7-2015')
insert into @temp values (115,'8-7-2015','8-10-2015')
-- i am passing 8 as month number in your case is August
select emp_num,
SUM(
DATEDIFF (DAY , startdate,
case when MONTH(enddate) = 8
then enddate
else DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,startdate)+1,0))--end date of month
end
)+1) AS Vacation from @temp
where (month(startdate) = 8 OR month(enddate) = 8) AND (Year(enddate)=2015 AND Year(enddate)=2015)
group by emp_num
更新有效评论后:此操作将在以下日期失败:2015-07-01、2015-09-30 –@t-clausen.dk
我以为OP只想要一个月,他会通过
declare @temp table
(emp_num int, startdate date, enddate date)
insert into @temp values (234,'8-2-2015','8-5-2015')
insert into @temp values (234,'6-28-2015','7-1-2015')
insert into @temp values (234,'8-29-2015','9-2-2015')
insert into @temp values (115,'6-7-2015','6-7-2015')
insert into @temp values (115,'8-7-2015','8-10-2015')
insert into @temp values (116,'07-01-2015','9-30-2015')
select emp_num,
SUM(
DATEDIFF (DAY , startdate,
case when MONTH(enddate) = 8
then enddate
else DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,startdate)+1,0))
end
)+1) AS Vacation from @temp
where (Year(enddate)=2015 AND Year(enddate)=2015)
AND 8 between MONTH(startdate) AND MONTH(enddate)
group by emp_num
关于sql - 如何获取范围内一年中特定月份的天数总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32607363/