Dense_rank和总和

时间:2013-10-07 11:27:38

标签: sql stored-procedures

我有这个常见的表格表达式

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的总小时等等。

由于

1 个答案:

答案 0 :(得分: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,如果这是您需要的。