SQL Server中每列的行值总计

时间:2019-07-05 17:02:13

标签: sql sql-server

我有一个查询,该查询返回员工工作了一天的DateTime跨度,该时间与一年中的哪个星期有关以及跨度的日期。效果确实不错,但我想计算特定一周内每天的运行总计。

当前,我的查询如下:

SELECT A.*
FROM (
    SELECT WeekNumber, SUM(NumberOfSecondsWorked) AS NumberOfSecondsWorkedInDay, MIN(FromTime) AS StartOfDay, MAX(ToTime) AS EndOfDay, (SELECT WeeklyTotal = SUM(NumberOfSecondsWorked) FROM #temp AS T2 WHERE T2.WeekNumber = T1.WeekNumber) AS WeeklyTotal
    FROM #temp AS T1 GROUP BY DayMonth, WeekNumber) A

并返回此:

enter image description here

我遇到的问题是,我希望每周按行对每周总计进行汇总,因此数据如下所示:

enter image description here

每行每周总计。谁能告诉我我在查询中做错了什么?

2 个答案:

答案 0 :(得分:3)

您的查询和您的结果集并不一致。例如,您的结果集包含StartOfDay

但是,您似乎想要:

SELECT WeekNumber, SUM(NumberOfSecondsWorked) AS NumberOfSecondsWorkedInDay,
       MIN(FromTime) AS StartOfDay, MAX(ToTime) AS EndOfDay,
       SUM(SUM(NumberOfSecondsWorked)) OVER (PARTITION BY WeekNumber ORDER BY MIN(FromTime))
FROM #temp AS T1
GROUP BY DayMonth, WeekNumber;

编辑:

在SQL Server 2008中,您需要使用其他方法,例如相关子查询:

WITH wn as (
      SELECT WeekNumber, SUM(NumberOfSecondsWorked) AS NumberOfSecondsWorkedInDay,
             MIN(FromTime) AS StartOfDay, MAX(ToTime) AS EndOfDay
      FROM #temp T1
      GROUP BY DayMonth, WeekNumber
     )
SELECT wn.*,
       (SELECT SUM(wn2.NumberOfSecondsWorked)
        FROM wn wn2
        WHERE wn2.WeekNumber = wn.WeekNumber AND
              wn2.FromTime <= wn.FromTime
       )
FROM wn;

答案 1 :(得分:1)

通过使用窗口函数尝试以下操作

     SELECT WeekNumber,
     SUM(NumberOfSecondsWorked) AS NumberOfSecondsWorkedInDay,
     MIN(FromTime) AS StartOfDay, MAX(ToTime) AS EndOfDay,
     SUM(NumberOfSecondsWorked) over( order by WeekNumber) AS WeeklyTotal
    FROM #temp AS T1
    GROUP BY DayMonth, WeekNumber