SQL查询过去8周内的总请求数

时间:2018-04-04 13:25:43

标签: sql sql-server stored-procedures

我正在处理一个查询,该查询显示过去8周内按周划分的未结支持请求数量细分。我在SO上找到了几个答案,并改变了一些东西来满足我的需求。

我已经获取数据并将其转向以显示细分。但是,我收到一个关于createdDate不在聚合函数中的错误,我不知道我需要把它放在哪里。

示例:

Declare @DatePeriod DATETIME = GETUTCDATE()

Select  IsNull([1],0) as 'Week 1',
        IsNull([2],0) as 'Week 2',
        IsNull([3],0) as 'Week 3',
        IsNull([4],0) as 'Week 4',
        IsNull([5],0) as 'Week 5',
        IsNull([6],0) as 'Week 6',
        IsNull([7],0) as 'Week 7',
        IsNull([8],0) as 'Week 8'
From 
(
Select  
        DATEDIFF(week, DATEADD(MONTH, DATEDIFF(MONTH, 0, createdDate), 0), createdDate) +1 as [Weeks],
        COUNT(reqID) as 'TotalOpened'

From support_tickets
Where DatePart(Month, createdDate)= DatePart(Month, @DatePeriod)
AND tool = 244
)p 
Pivot (COUNT(TotalOpened) for Weeks in ([1],[2],[3],[4],[5],[6],[7],[8])) as pv

如果我还要转动数据,有人可以指出我需要添加分组的位置吗?

Column 'support_tickets.createdDate' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

1 个答案:

答案 0 :(得分:1)

添加:

GROUP BY DATEDIFF(week, DATEADD(MONTH, DATEDIFF(MONTH, 0, createdDate), 0), createdDate) +1

之后:

AND tool = 244