分组使用包含特定值的列

时间:2014-10-01 17:30:38

标签: sql tsql count group-by

我一直在尝试构建一个视图,按年份和月份对包含特定值的记录进行分组和计数,但我对这个问题感到困惑,并希望有人能够帮助我。 我有一张名为LNCARR的表格,如下所示:

VerDate    | RootCauseCategory
----------------------------------------------------------------
2014-07-01 | Handling; Tooling; Training
2014-07-24 | Supplier; Handling; Tooling
2014-07-22 | Handling; Tooling; Training
2014-08-02 | Work Instructions; Workmanship; Quality System Implementation
2014-08-19 | Workmanship; Sampling Plan

我想构建一个类似下面的视图,显示每月RootCauseCategory事件的发生次数:

Year  | Month  | RootCauseCategory                  | Count
-----------------------------------------------------------------
2014  | 07     | Handling                           | 3
2014  | 07     | Supplier                           | 1
2014  | 07     | Tooling                            | 3
2014  | 07     | Training                           | 2
2014  | 08     | Quality System Implementation      | 1
2014  | 08     | Sampling Plan                      | 1
2014  | 08     | Work Instructions                  | 1
2014  | 08     | Worksmanship                       | 2

例如,在07-2014中,RootCauseCategory'工具'包含在3条记录中,因此它的计数为3。 我已经得到了下面的代码,它将按年,月和整个RootCauseCategory对记录进行分组和计数(例如2014 | 07 |处理;工具;培训| 2),但我似乎无法理解弄清楚如何按每次出现的RootCauseCategory分组行,如上所述

SELECT *, COUNT(*) AS Count
FROM   ( SELECT    YEAR(VerDate) AS Year ,
                MONTH(VerDate) AS Month ,
                RootCauseCategory                   
      FROM dbo.LNCARR
    ) AS Result
GROUP BY Year, Month, Result.RootCauseCategory
ORDER BY YEAR DESC, month, Result.RootCauseCategory

有没有办法做到这一点?

1 个答案:

答案 0 :(得分:1)

您可以创建一个解析字符串的函数。然后使用Cross Apply更新选择。

select cast('2014-07-01' as date) as VerDate, cast('Handling; Tooling; Training' as varchar(200)) as RootCauseCategory
  into LNCARR

INSERT INTO [dbo].[LNCARR]
           ([VerDate]
           ,[RootCauseCategory])
     VALUES
           ('2014-07-24', 'Supplier; Handling; Tooling')
          ,('2014-07-22', 'Handling; Tooling; Training')
          ,('2014-08-02', 'Work Instructions; Workmanship; Quality System Implementation')
          ,('2014-08-19', 'Workmanship; Sampling Plan')

GO

Create Function ufnGetCategoy(@RCC varchar(200))
Returns @Category Table
(Category varchar(200))
as

Begin
    Declare @x int = 1
           ,@str varchar(200) = @RCC + ';'

    While @x < LEN(rtrim(@RCC))
    begin

    insert into @Category
      values (ltrim(rtrim(substring(@str, @x, charindex(';', @str, @x) - @x))))
    set @x = (charindex(';', @str, @x) + 1)
    end -- While

    Return

End; --Function ufnGetCategoy
go

SELECT *, COUNT(*) AS Count
FROM   ( SELECT    YEAR(VerDate) AS Year ,
                MONTH(VerDate) AS Month ,
                Category                   
      FROM dbo.LNCARR
      cross apply dbo.ufnGetCategoy(RootCauseCategory)
    ) AS Result
GROUP BY Year, Month, Category
ORDER BY YEAR DESC, month, Category