SQL:按日期时间字段分组,但仅使用日期和查询中其他位置使用的日期

时间:2016-02-10 15:27:12

标签: sql

我正在努力使这个查询正确。

SELECT CallCategory, COUNT(CallCategory) as Total

,SUBSTRING(DATENAME(DW, ResolvedDate), 1, 3) As 'Day'
,SUBSTRING(DATENAME(DW, ResolvedDate), 1, 3) As 'Day'
,DATEPART(WEEK, ResolvedDate) As 'Week'
,CONVERT(CHAR(3), ResolvedDate, 0) As 'Month'
,DATEPART(YEAR, ResolvedDate) As 'Year'

,DATEPART(WEEK, GETDATE()) As CurrentWeek
,CONVERT(CHAR(3), GETDATE(), 0) As CurrentMonth
,DATEPART(YEAR, GETDATE()) As CurrentYear


,Case When DATEPART(WEEK, ResolvedDate) = DATEPART(WEEK, GETDATE()) Then 'Yes' Else 'No' End As IsThisWeek

,Case When DATEPART(WEEK, ResolvedDate) = DATEPART(WEEK, GETDATE()) -1 Then 'Yes' Else 'No' End As IsLastWeek

,Case When CONVERT(CHAR(3), ResolvedDate, 0) = CONVERT(CHAR(3), GETDATE()) Then 'Yes' Else 'No' End As IsThisMonth

,Case When DATEPART(YEAR, ResolvedDate) = DATEPART(YEAR, GETDATE()) Then 'Yes' Else 'No' End As IsThisYear

,Case When DATEPART(yy, ResolvedDate) = DATEPART(yy, GETDATE()) and DATEPART(mm, ResolvedDate) = DATEPART(mm, GETDATE()) and DATEPART(dd, ResolvedDate) = DATEPART(dd, GETDATE())
Then 'Yes' Else 'No' End As IsToday

,case when DATEPART(WEEK, convert(date,ResolvedDate, 105)) = DATEPART(WEEK, GETDATE()) -4 then 'Yes' else 'No' end as MonthOld

FROM prcDepartmentHelpDesks WHERE SupportTeam = 'Some Team' AND ResolvedDate >=   '2016-02-09'

GROUP BY  CAST(ResolvedDate AS DATE) , CallCategory

它一直要求我将ResolvedDate添加到聚合中或添加到组中。如果我将案例和日期部分注释掉,那么它就可以了。

1 个答案:

答案 0 :(得分:0)

你按CAST(ResolvedDate AS DATE)分组 - 据说是因为尽管名称ResolvedDate不是日期而是日期时间,你想要摆脱时间部分。

因此,您按日期分组,并且当同一日期的一个调用类别有两条记录时,您希望为它们获取一条结果记录并计数2.但是,在SELECT子句中,您指的是{{1例如在这里:ResolvedDate。但是什么 DATEPART(WEEK, ResolvedDate) As 'Week'?该组有两个不同的日期时间。这意味着您无法再访问SELECT子句中的ResolvedDate,只能访问ResolvedDate

因此,您可以通过在SELECT子句中将所有CAST(ResolvedDate AS DATE)替换为ResolvedDate来解决您的问题。但是,抛出一次并处理此结果(即使用派生表,FROM子句中的子查询)可能更方便。您的查询将如下所示:

CAST(ResolvedDate AS DATE)

我已经纠正了一些评估,例如:将这一年纳入IsThisWeek的考虑范围。可能仍然有错误,我忘了删除或我甚至介绍。仔细看看这些公式并确定它们是否适合你。