2012-08-02 108 views
1

我正在参加asp.net的考勤软件,在这里我必须做一个报告,告诉用户有关小时和一切...迄今为止,我已经创建了基本功能的系统,即用户可以检查和结帐...我被困在做报告...计算一个月的工作时间

我必须计算每个月的工作时间,因此用户可以比较他的小时与总小时数......我想到的是创建一个存储过程,当给定一个月名称和一年时,返回一个包含该月份工作时间的int ......但我似乎可以得到它...... 。

迄今为止,我发现如何创建一个给定月份的日期和一个日期,并找出了该月的最后一天,使用我可以找出在月的总天数...现在我似乎无法弄清楚我怎么知道多少天减去获得工作日。

这里是到目前为止代码..

declare 
@y int, 
@m int, 
@d int, 
@date datetime 


set @y = 2012 
set @m = 01 
set @d = 01 

----To create the date first 
select @date = dateadd(mm,(@y-1900)* 12 + @m - 1,0) + (@d-1) 
----Last Day of that date 
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@date)+1,0)) 

任何帮助将不胜感激你们,谢谢提前....

+2

请注意这里。一个工作日的定义是什么?周一至周五?那么兼职工作者,周末工作者,银行假期,建筑物关闭的日子,培训日等等呢?我的经验表明,您最灵活的方法是创建一个充当日历的表格 - 您可以预先填充当天可以*工作的小时数,当天可以*正常工作的小时数的地方,实际上*能够*当天工作,并且当天*实际上*工作。那么你有数据而不是算法,数据可以适应非常规情况。 – MatBailie 2012-08-02 09:53:58

回答

1

的@theDate是要计算每月的任何日期工作日。这种方法不关心假期。

DECLARE @theDate DATETIME = GETDATE() 
SELECT MONTH(@theDate) [Month], 20 + COUNT(*) WorkDays 
    FROM (
     SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, @theDate), 28) AS theDate 
      UNION 
     SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, @theDate), 29) 
      UNION 
     SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, @theDate), 30) 
     ) AS d 
WHERE DATEPART(DAY, theDate) > 28 
    AND DATEDIFF(DAY, 0, theDate) % 7 < 5 
+0

答案是否足够好并解决了您的问题?然后接受它作为答案 – Yaroslav 2012-08-02 13:19:38

0

在这里,您可以考虑下面的SQL Server代码来获取给定月份的第一和 最后一天,也忽略所有的星期六和星期日。

DECLARE @curr_date datetime=getdate() 
    DECLARE @st_date datetime,@ed_date datetime 
    select @st_date=DATEADD(mm,datediff(mm,0,@curr_date),0),@ed_date = DATEADD(mm,datediff(mm,-1,@curr_date),-1) 
    --select @st_date as first_day,@ed_date as last_day 

    SET DATEFIRST 1 --Monday as first day of week 
    select DATEADD(dd,number,@st_date) from master..spt_values 
    where DATEDIFF(dd,DATEADD(dd,number,@st_date),@ed_date) >= 0 and type='P' 
    and DATEPART(DW,DATEADD(dd,number,@st_date)) <> 6 
    and DATEPART(DW,DATEADD(dd,number,@st_date)) <> 7 

But inorder to calculate the actual working hours, you will have to take into the consideration of following thigs 

1.Calculate the time interval between swipe-in and swipe-outs between start and end time for a day. 
2.Exclude all the time gap(employee not in office) 
3.Consider the company holidays. 
etc 
0

这里是UDF来计算工作日。您可以将一个月的任何日期传递给此功能。但通常您应该使用实际的“日历”表来计算工作日,并在周末,节假日等...中插入此表。

CREATE FUNCTION dbo.WorkDaysCount (@Date datetime) 
RETURNS int AS 
BEGIN 

DECLARE @BeginOfMonth datetime 
SET @BeginOfMonth=DATEADD(DAY,-DAY(@Date)+1,@Date); 

DECLARE @EndOfMonth datetime 
SET @EndOfMonth=DATEADD(Day,-1,DATEADD(Month,1,@BeginOfMonth)); 

DECLARE @cDate datetime 
set @[email protected] 

Declare @WorkDaysCount int 
SET @WorkDaysCount=0 

while @cDate<[email protected] 
begin 
    if DATEPART(dw,@cDate) not in (1,7) SET @[email protected]+1 -- not a Sunday or Saturday change (1,7) to (6,7) if you have other week start day (Monday). 
    set @[email protected]+1; 
end; 

return (@WorkDaysCount); 

END