如何使用sql每周对每日数据进行分组

时间:2014-03-27 17:37:18

标签: sql sql-server tsql

我正在尝试对过去4周内员工工作的小时数进行分组,但我希望每周对他们进行分组。例如:

WEEK                    HOURS
Feb 24 to March 2         55
March 3 to March 9        40
March 10 to March 16      48
March 17 to March 23      37

这是我到目前为止,请帮助。感谢

SET DATEFIRST 1

    SELECT CAST(MIN( [DT]) AS VARCHAR(20))+' TO '+CAST (MAX([DT]) AS VARCHAR(20)) AS DATE,
           SUM(HOURS) AS NUM_HRS
    FROM   MyTable
    GROUP BY DATEPART(WEEK,[DT])
    HAVING COUNT(DISTINCT[DT])=7

3 个答案:

答案 0 :(得分:1)

创建一个日历辅助表,其中包含年,月,周,日期列(您还可以添加假期和其他有趣的内容,它有许多潜在的用途)并在感兴趣的时段填充它。

在那之后,它就像这样简单:

SELECT sum(hours), cast(min(date) as varchar), cast(max(date) as varchar)
FROM Calendar c
LEFT OUTER JOIN MyTable h on h.Date = c.date
GROUP BY year, week
ORDER BY year, week

答案 1 :(得分:1)

SET DATEFIRST 1

    SELECT DATEPART(WEEK,DT) AS WEEK,
           SUM(HOURS) AS NUM_HRS
    FROM   MyTable
    WHERE DT >= DATEADD(WEEK, -4, GetDate()),
    GROUP BY DATEPART(WEEK,[DT])

答案 2 :(得分:0)

尝试类似

的内容
SELECT
    DATEADD(DD, 
            CONVERT(INT, (DATEDIFF(DD, '1/1/1900', t.DT)/7)) * 7, 
           '1/1/1900') [WeekBeginDate],
    DATEADD(DD,
            (CONVERT(INT, (DATEDIFF(DD, '1/1/1900', t.DT)/7)) * 7) + 6,
           '1/1/1900') [WeekEndDate],
    SUM(HOURS) AS NUM_HRS
FROM MyTable t
GROUP BY CONVERT(INT, DATEDIFF(DD, '1/1/1900', t.DT)/7)

虽然这是蛮力技巧,但我认为在你的情况下它会起作用。

编辑:稍微修改了查询,错误是由DATEDIFF计算差异的顺序引起的。

这里还有一个SQL FIDDLE,其中有一个工作示例。

编辑2:使用日期格式更新了小提琴。要自定义日期格式,this article会有所帮助。