SQL帮助计算项目计费的常规和加班时间

时间:2015-07-21 11:31:00

标签: sql sql-server tsql

我的表格看起来像这样

First Name  Last Name   Date    Day Hours   Project Name
Joe         Smith     6/22/15   Mon 8       Project A
Joe         Smith     6/23/15   Tue 11.75   Project A
Joe         Smith     6/24/15   Wed 10.25   Project A
Joe         Smith     6/25/15   Thu 14.25   Project B
Joe         Smith     6/26/15   Fri 11.5    Project B
Joe         Smith     6/27/15   Sat 9.5     Project B
Joe         Smith    6/28/15    Sun 8.53    Project B

我需要为每位员工计算常规时间和加班时间,每个项目都有效。

常规时间:本周的所有工作日小时数小于或等于40小时 加班:每周工作时间超过40小时,任何周末时间

我的结果应该是这样的

Firstname   Lastname    Date    Day Regular OverTime    Project Name
Joe          Smith     6/22/15  Mon 8.00                 Project A
Joe          Smith     6/23/15  Tue 11.75                Project A
Joe          Smith     6/24/15  Wed 10.25                Project A
Joe          Smith     6/25/15  Thu 10.00   4.25         Project B
Joe          Smith     6/26/15  Fri 0.00    11.50        Project B
Joe          Smith     6/27/15  Sat 0.00    9.50         Project B
Joe          Smith     6/28/15  Sun 0.00    8.53         Project B
--------------------------------------------------------------------
    Total                           40.00   33.78   

我无法达到这个结果。

1 个答案:

答案 0 :(得分:1)

对于SQL服务器,下面的代码将起作用。请注意,我使用COALESCE关键字来封装OverTime和Regular hours计算的业务逻辑。 对于这些计算,我需要使用内部查询计算的一周中的累积小时数,以及当小时数超过40时我需要识别拐点。

SELECT 
Q.FirstName, 
Q.LastName,
Q.[Date],
Q.Day,
COALESCE(
      CASE 
         WHEN Q.[Day] like 's%' THEN 0 ELSE NULL END,
       CASE 
         WHEN Q.Cumulative>40 AND Q.cumulative-Q.hours>40 
         THEN 0 ELSE NULL END,
       CASE 
          WHEN Q.Cumulative>40 AND Q.cumulative-Q.hours<40 
          THEN 40-Q.cumulative+ Q.hours ELSE Q.hours END
        ) AS Regular,
COALESCE(
      CASE 
         WHEN Q.[Day] like 's%' THEN Q.Hours ELSE NULL END,
       CASE 
         WHEN Q.Cumulative>40 AND Q.cumulative-Q.hours>40
         THEN Q.hours ELSE NULL END,
       CASE 
          WHEN Q.Cumulative>40 AND Q.cumulative-Q.hours<40 
          THEN Q.Cumulative-40 ELSE 0 END
        ) AS OverTime,
Q.[Project Name]
FROM
(SELECT 
B.FirstName,
B.LastName,
B.[Date],
B.Day,
B.hours,
B.[Project Name],
(SELECT SUM(A.hours) FROM  [dbo].[temp] A WHERE A.[Date]<=B.[Date]) cumulative
FROM [dbo].[temp] B )Q

Sql fiddle link http://sqlfiddle.com/#!18/7eea7/2