4

我正在尝试按周对一系列日期进行分组。到目前为止,我有以下内容:

SELECT  DATEPART(week, CONVERT(VARCHAR(50), e.event_date, 107)) AS 'Date' ,
        c.setting_secondary AS 'Workflow Cat' ,
        d.setting_main AS 'Error Type' ,
        SUM(e.event_count) AS 'Total'
FROM    marlin.support_events AS e
        INNER JOIN marlin.support_config AS c
            ON e.event_category = c.setting_code
            AND config_code = 60
        INNER JOIN marlin.support_config AS d
            ON e.event_type = d.setting_code
            AND d.config_code = 70
WHERE   e.event_date BETWEEN DATEADD(MONTH, -2, GETDATE()) AND GETDATE()
        AND c.setting_secondary = 'Expenditure Voucher'
        AND d.setting_main IN ( 'Unstarted' , 'Timeout' )
GROUP BY
        DATEPART(week, CONVERT(VARCHAR(50), e.event_date, 107)) ,
        c.setting_secondary ,
        d.setting_main ,
        e.event_summary

这向我显示了周数,但不显示该周开始的日期,如下所示:

在此处输入图像描述

如何显示本周开始的日期?

回答:

下面确定的答案以及我还找到了另一种方法:

DATEADD(dd, -(DATEPART(dw, e.event_date)-1), e.event_date) 
4

1 回答 1

4

您可以从日期中获取年份部分,附加第一个月的第一天,然后添加(#week - 1)以获取 event_date 所属的一周的开始日期,如下所示:

SELECT EventDate, WorkflowCat, ErrorType, SUM(EventCount) AS 'Total'
FROM
(
SELECT  DATEADD(ww, 
           DATEPART(ww, e.event_date) - 1, 
           CONVERT(DATETIME, 
                   CONVERT(VARCHAR(4), DATEPART(yy, e.event_date)) + '-01-01')) AS 'EventDate' ,
        c.setting_secondary AS 'WorkflowCat' ,
        d.setting_main AS 'ErrorType',
        e.event_summary as 'EventSummary'
        e.event_count AS 'EventCount'
FROM    marlin.support_events AS e
        INNER JOIN marlin.support_config AS c
            ON e.event_category = c.setting_code
            AND config_code = 60
        INNER JOIN marlin.support_config AS d
            ON e.event_type = d.setting_code
            AND d.config_code = 70
WHERE   e.event_date BETWEEN DATEADD(MONTH, -2, GETDATE()) AND GETDATE()
        AND c.setting_secondary = 'Expenditure Voucher'
        AND d.setting_main IN ( 'Unstarted' , 'Timeout' )
)
GROUP BY EventDate, WorkflowCat, ErrorType, EventSummary
于 2012-11-09T04:22:34.883 回答