小编典典

按小时查询人工成本

sql

我知道如何按小时进行销售,因为我是根据销售的实际时间进行计算,而不是随着时间的流逝而进行分配。但是,鉴于以下数据,我试图找出按小时计算劳力的最佳方法。

EmployeeID  InTime   OutTime  PayRate  OTRate  DTRate
6           59:09.0  05:17.0  10.75    16.13   21.5
6           33:45.0  54:58.0  10.75    16.13   21.5
6           59:25.0  24:07.0  10.75    16.13   21.5
6           55:18.0  29:35.0  10.75    16.13   21.5
6           59:50.0  02:17.0  10.75    16.13   21.5
7           00:45.0  40:48.0  9.25     13.88   18.5
7           00:21.0  58:41.0  9.25     13.88   18.5
13          00:34.0  27:46.0  9        13.5    18
6           55:23.0  11:02.0  10.75    16.13   21.5
6           37:03.0  30:32.0  10.75    16.13   21.5

我知道我最终会弄清楚的,但是如果有人可以给我一些指导,以加快该过程并防止我做一些过于费解的事情,我一定会感激的。我需要使用此信息来做一些更复杂的报告,但首先,我只是在寻找最简单的查询,该查询将告诉我雇主每小时在人工上花费了多少。可以随意忽略加班/加班,因为我可以在弄清另一部分之后再将其合并。

编辑:InTime和OutTime字段实际上是DateTimes …由于某些原因,它在我复制/粘贴时会转换值

编辑:结果看起来像…

Hour   Labor Cost

1:00       $
2:00       $
3:00       $
4:00       $
5:00       $
etc.

$是该小时在人工上花费的金额。因此,我想做的第一件事是创建一个包含24行的表。每小时一个。然后,输入/输出时间将加入新表中的小时字段。只是想想一下这个连接表达式现在会是什么样子…

编辑:马克提醒我,我还需要同时显示日期和小时,这使我认为我的24行表实际上需要是24
*,但是我要查询的天数很多。另外,我意识到每小时1条记录并不能很好地工作,因为人们只能工作部分小时,因此我认为我需要每分钟进行一次记录,然后对这些结果进行分组/求和才能获得准确的数据。


阅读 181

收藏
2021-05-16

共1个答案

小编典典

当然未经测试,但是我认为这应该可以克服我所做的任何错别字:

-- Assume that there is a tblNumbers table
--  that has been populated with at least the values 0 to 60.
-- First, we need to find the days for which there are time records.
; WITH Days_cte (MyDay) AS
(
    SELECT DISTINCT
        -- Strip off the time from the date.  
        DATEADD(DAY, DATEDIFF(DAY, 0, InTime), 0) AS MyDay
    FROM tblTimeSheet

    UNION

    SELECT DISTINCT
        -- Strip off the time from the date.  
        DATEADD(DAY, DATEDIFF(DAY, 0, OutTime), 0) AS MyDay
    FROM tblTimeSheet
),
-- Next, explode this into hours AND minutes for every day.
-- This cte will contain 1440 records for every day.
Times_cte (MyTime) AS
(
    SELECT
        DATEADD(MINUTE, minutes.Number, 
                DATEADD(HOUR, hours.Number, days.MyDay)) AS MyTime
    FROM
        Days_cte days JOIN
        tblNumbers hours ON hours.Number < 24 JOIN
        tblNumbers minutes ON minutes.Number < 60 LEFT JOIN
)
-- Now, determine which of these minutes 
--  falls between an employee's in and out time.
SELECT
    -- Strip off the minutes, leaving only the hour.
    DATEADD(HOUR, DATEDIFF(HOUR, 0, times.MyTime), 0) AS [Hour],
    -- Divide by 60, since the aggregation is done by the minute.
    SUM(ISNULL(ts.PayRate, 0) / 60) AS LaborCost
FROM    
    Time_cte times LEFT JOIN
    tblTimeSheet ts ON times.MyTime BETWEEN ts.InTime AND ts.OutTime
GROUP BY
    DATEADD(HOUR, DATEDIFF(HOUR, 0, times.MyTime), 0)
2021-05-16