我可以找出每月事件的唯一解决者吗?

时间:2018-11-09 09:48:33

标签: sql-server-2008 casting 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

1 个答案:

答案 0 :(得分:0)

您有两种选择

  1. 要扩展结果并为MonthResolved,ResolvedByTeam和resolveby的每个唯一组合返回单独的行。这将返回比原始查询更多的行,因为在一个月/团队的组合中,您将获得与解析器一样多的行。
  2. 要在查询中增加一列,在其中返回包含解析器名称的列表(例如,逗号分隔)。使用STRING_AGG函数可以轻松完成此操作,但仅在SQL Server 2017和更高版本中可用。对于2008年,您可以选择使用FOR XML子句执行一些难看的转换。

这里都是用于实现选项1和2的查询。

;with cte1 as (
SELECT
    CAST(DATEPART(year, stat_datetimeresolved) as varchar(4)) + '-' + RIGHT('0' + CAST(DATEPART(month, stat_datetimeresolved) as varchar(2)), 2) as MonthResolved
    , ResolvedByTeam
    , resolvedby
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, resolvedby
)
select
    MonthResolved
    , ResolvedByTeam
    , (select count(distinct resolvedby) as Name
       from [dbo].[Incident] i 
       where CAST(DATEPART(year, stat_datetimeresolved) as varchar(4)) + '-' + RIGHT('0' + CAST(DATEPART(month, stat_datetimeresolved) as varchar(2)), 2) = cte1.MonthResolved
         and i.ResolvedByTeam = cte1.ResolvedByTeam)
    , resolvedby
from cte1
ORDER BY MonthResolved asc, ResolvedByTeam, resolvedby

;with cte2 as (
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
)

select *
from cte2
cross apply (select (
    select distinct resolvedby + ', ' as [text()]
    from [dbo].[Incident] 
    where ResolvedByTeam = cte2.ResolvedByTeam
        and CAST(DATEPART(year, stat_datetimeresolved) as varchar(4)) + '-' + RIGHT('0' + CAST(DATEPART(month, stat_datetimeresolved) as varchar(2)), 2) = cte2.MonthResolved
    for xml path ('')) as Names) t
ORDER BY MonthResolved asc, ResolvedByTeam