如何每月显示团队中的个人解决方案

时间:2018-11-08 10:31:42

标签: sql-server-2008 casting count distinct sql-view

我目前有一个SQL视图,该视图使用以下代码显示自2017年4月以来每天每个团队中有多少人制定了解决方案。我将如何修改它,以便我可以按月而不是每天进行?

SELECT CAST(stat_datetimeresolved as date) as DateResolved, ResolvedByTeam, COUNT(DISTINCT resolvedby) as ResolvedByCnt
FROM [dbo].[Incident]
 WHERE Stat_DateTimeResolved >= '20170401'
GROUP BY CAST(Stat_DateTimeResolved as DATE), ResolvedByTeam
ORDER BY CAST(stat_datetimeresolved as DATE) asc, ResolvedByTeam

1 个答案:

答案 0 :(得分:0)

您可以设置日期格式,使其仅显示为年份和月份:

select format(getdate(), 'yyyyMM')

然后按此值分组。因此,您的查询应如下所示:

SELECT FORMAT(stat_datetimeresolved, 'yyyyMM') as MonthResolved, ResolvedByTeam, COUNT(DISTINCT resolvedby) as ResolvedByCnt
FROM [dbo].[Incident]
 WHERE Stat_DateTimeResolved >= '20170401'
GROUP BY FORMAT(stat_datetimeresolved, 'yyyyMM'), ResolvedByTeam
ORDER BY MonthResolved asc, ResolvedByTeam

更新:对于2012之前的版本,可以使用DATEPART函数构造年份-月份部分。在这种情况下,查询可能如下所示:

SELECT CAST(DATEPART(year, stat_datetimeresolved) as varchar(4)) + '-' + RIGHT('0' + CAST(DATEPART(month, stat_datetimeresolved) as varchar(2)), 2) as MonthResolved, ResolvedByTeam, COUNT(DISTINCT resolvedby) as ResolvedByCnt
FROM [dbo].[Incident]
 WHERE stat_datetimeresolved >= '20170401'
GROUP BY CAST(DATEPART(year, stat_datetimeresolved) as varchar(4)) + '-' + RIGHT('0' + CAST(DATEPART(month, stat_datetimeresolved) as varchar(2)), 2), ResolvedByTeam
ORDER BY MonthResolved asc, ResolvedByTeam

SELECT convert(char(6), Stat_DateTimeResolved , 112) as MonthResolved, ResolvedByTeam, COUNT(DISTINCT resolvedby) as ResolvedByCnt
FROM [dbo].[Incident]
 WHERE Stat_DateTimeResolved >= '20170401'
GROUP BY convert(char(6), Stat_DateTimeResolved , 112), ResolvedByTeam
ORDER BY MonthResolved asc, ResolvedByTeam