2012-08-02 105 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