我正在构建一个SQL函数,该函数根据一个人的开始日期和结束日期来计算一个人的总工作时间。
例如:
开始日期-------结束日期---------小时
2015年3月1日-------- 2015年3月31日--------- 100
2015年4月1日-------- 2015年4月30日--------- 100
2015年5月1日-------- 2015年5月31日--------- 130
...
问题是我无法在日历的开始和结束日期之前执行此操作。 (即1月至12月),必须按会计开始和结束日期。
这需要从该人的开始日期(2015年3月1日)到该日期之后的12个月(2016年3月1日)。
SELECT year(StartDate), SUM(Hours)
from EmployeeHours
WHERE EmployeeID = 12345
group by year(StartDate)
order by year(StartDate) desc
因此,此代码正确返回每年的总和,但它基于日历年。
有人对我如何实现这一目标有任何建议吗?
谢谢!
答案 0 :(得分:0)
您必须创建一个会计年度,该会计年度可以是当前年度,也可以是+1年,具体取决于您所在的月份。
declare @EmployeeHours table (EmployeeId int not null, startdate date not null, enddate date not null, [hours] int not null)
insert into @EmployeeHours (EmployeeId, startdate, enddate, [hours]) values
(12345, '2015-2-1', '2015-2-28', 100)
, (12345, '2015-3-1', '2015-3-31', 100)
, (12345, '2015-4-1', '2015-4-30', 100)
, (12345, '2015-5-1', '2015-5-31', 130)
SELECT datepart(year, startdate) + iif(DATEPART(MONTH, StartDate) > 2, 1,0) as [fiscalyear], SUM([Hours])
from @EmployeeHours
WHERE EmployeeID = 12345
group by datepart(year, startdate) + iif(DATEPART(MONTH, StartDate) > 2, 1,0)
order by 1 desc
输出
2016 330
2015 100
答案 1 :(得分:0)
尝试一下
create table #temp(StartDate datetime, EndDate datetime, Hours int)
insert into #temp values
('3/1/2015','3/31/2015' , 100)
,('4/1/2015','4/30/2015' , 100 )
,('5/1/2015','5/31/2015', 130 )
Declare @sDate dateTime='2015-03-01'
Declare @EDate dateTime='2016-03-01'
SELECT year(StartDate), SUM(Hours)
from #temp
WHERE
--EmployeeID = 12345
--and
StartDate>=@sDate and EndDate<=@EDate
group by year(StartDate)
order by year(StartDate) desc
drop table #temp