SQL服务器,如何根据星期几求和

SQL Server, how to sum based on day of the week

我有一个 table 可以保持出勤率。它包含三列:

createdby (varchar(30))
TimeSheetDate (dateTime)
Workinghours (integer)

我想计算一周中一天的工作时间总和。例如

Monday   Tuesday    Wednesday
------------------------------
10        9         11

我很难获得基于 DOW 的总数。

这是我的查询:

SELECT 
    createdby,
    CASE 
        WHEN dbo.udf_DayOfWeek(TimeSheetDate) = 'Monday'  
           THEN sum(WorkingHours) as Monday 
        WHEN dbo.udf_DayOfWeek(TimeSheetDate) = 'Tuesday' 
           THEN sum(WorkingHours) as Tuesday
        WHEN dbo.udf_DayOfWeek(TimeSheetDate) = 'Wednesday' 
           THEN sum(WorkingHours) as Wednesday
        WHEN dbo.udf_DayOfWeek(TimeSheetDate) = 'Thursday' 
           THEN sum(WorkingHours) as Thursday
    End 
FROM 
    TS.TimesheetsDetails
WHERE 
    CreatedDate <= '2014-09-26' AND 
    CreatedDate >= '2014-09-19' 
GROUP BY 
    createdby, dbo.udf_DayOfWeek(TimeSheetDate)

但是不行,报错

谁能给点正确的指导? 顺便说一下函数 udf_DayOfWeek() returns 星期几。

试试这个

但我不确定

     SELECT createdby, CASE WHEN dbo.udf_DayOfWeek(TimeSheetDate)='Monday' THEN sum(WorkingHours) end as Monday,case WHEN dbo.udf_DayOfWeek(TimeSheetDate)='Tuesday' THEN sum(WorkingHours) end as Tuesday,case WHEN dbo.udf_DayOfWeek(TimeSheetDate)='Wednesday' THEN sum(WorkingHours) end as Wednesday,case  WHEN dbo.udf_DayOfWeek(TimeSheetDate)='Thursday' THEN sum(WorkingHours) end as Thursday

 FROM TS.TimesheetsDetails WHERE CreatedDate <='2014-09-26' and CreatedDate>='2014-09-19' GROUP BY createdby, dbo.udf_DayOfWeek(TimeSheetDate)`

这看起来像是条件求和。关键是 columns 不能是有条件的,只是聚合中的 value 。所以你必须把 case 语句放在 SUM():

select createdby,
    sum(case when dbo.udf_DayOfWeek(TimeSheetDate)='Monday' then WorkingHours else 0 end) as Monday,
    sum(case when dbo.udf_DayOfWeek(TimeSheetDate)='Tuesday' then WorkingHours else 0 end) as Tuesday,
    ...
from TS.TimesheetsDetails
where CreatedDate between '2014-09-19' and '2014-09-26'
group by createdby

注意 1:我不明白为什么要按星期几分组,如果您也想按星期几进行汇总。我已经删除了它。

注意 2:我不确定您为什么使用 UDF 而不是内置 DATEPART 函数来获取星期几。


或者,您可以旋转它,可以说,它看起来更干净:

select createdby, Monday, Tuesday, ...
from (
    select createdby, dbo.udf_DayOfWeek(TimeSheetDate) as dow, WorkingHours
    from TS.TimesheetsDetails
    where CreatedDate between '2014-09-19' and '2014-09-26'
) x
pivot (
    sum(WorkingHours)
    for dow in ([Monday],[Tuesday],...)
) p