0

我有这个公用表表达式

WITH total_hour
AS (
    SELECT 
      employee_id,
      SUM(ROUND(CAST(DATEDIFF(MINUTE, start_time, finish_time) AS NUMERIC(18, 0)) / 60, 2)) AS total_h
    FROM Timesheet t
    WHERE t.employee_id = @employee_id
      AND DENSE_RANK() OVER (
        ORDER BY DATEDIFF(DAY, '20130925', date_worked) / 7 DESC ) = @rank
    GROUP BY t.personnel_id
    )

这是样本数据:

ID  employee_id     worked_date     start_time      finish_time
 1     1          2013-09-25        09:00:00    17:30:00        
 2     1          2013-09-26        07:00:00    17:00:00    
 8     1          2013-10-01        09:00:00    17:00:00    
 9     1          2013-10-04        09:00:00    17:00:00    
 12    1          2013-10-07        09:00:00    17:00:00    
 13    1          2013-10-30        09:00:00    17:00:00    
 14    1          2013-10-28        09:00:00    17:00:00    
 15    1          2013-11-01        09:00:00    17:00:00

假设星期三是一周的第一天,我的基准日期是 2013-09-25。当@rank 为 1 时,我想获得从 09-25 到 10-01 的总小时数,以及当 @rank=2 时从 10-02 到 10-08 的总小时数,依此类推。

谢谢

4

1 回答 1

1

要获得员工在特定周内的工作小时数,只需使用合适的 WHERE 标准。无需为此使用 DENSE_RANK 或类似的窗口函数。

假设你有一个 @Week 参数,它包含一个整数(0 代表本周,1 代表上周,2 代表前一周,等等):

SELECT
    employee_id
    SUM(ROUND(CAST(DATEDIFF(MINUTE, start_time, finish_time) AS NUMERIC(18, 0)) / 60, 2)) AS total_h
FROM
    Timesheet t
WHERE
    t.employee_id = @employee_id AND
    date_worked BETWEEN DATEADD(ww, DATEDIFF(ww,0,GETDATE()) - @Week, 0)
                    AND DATEADD(ww, DATEDIFF(ww,0,GETDATE()) - @Week, 0) + 7

在这里,我使用当前日期 ( GETDATE()) 作为基准日期,但如果需要,您可以将其替换为20130925

于 2013-10-07T12:09:20.437 回答