将行组合为重复值

时间:2016-10-18 08:00:39

标签: sql-server

我目前正在尝试计算一个文章类别在故障单表格中出现的次数 问题是类别有子类别,它们都在表格中列为单个字符串(“Cat1> Subcat1”,“Cat1> Subcat2”等)。

我到目前为止所做的工作是设法列出所有不同的类别,但我想从结果中删除任何子类别并合并任何副本。

例如,我有以下类别和计数:

  

类别| 13个
  分类> Subcat1 | 14个
  分类> Subcat2 | 3

我想看到的是:

  

类别| 30

到目前为止,我已设法剥离子类别,但实际行基本上是重复的,具有不同的值:

  

类别| 13个
  类别| 14   类别| 3

这是我目前的代码:

SELECT 
CASE
    WHEN CHARINDEX(' >',SUBSTRING(KM2.GENERATEDCATS,16,20))=0 
    THEN SUBSTRING(KM2.GENERATEDCATS,16,20) 
    ELSE SUBSTRING(SUBSTRING(KM2.GENERATEDCATS,16,20),1,CHARINDEX(' >',SUBSTRING(KM2.GENERATEDCATS,16,20)))
END AS "Final",
COUNT(KM2.GENERATEDCATS) AS "Count"

FROM INCIDENTSM1 AS SD LEFT JOIN KMDOCUMENTM1 AS KM1 ON SD.CBA_KPF_ID=KM1.ID
LEFT JOIN KMDOCUMENTA2 AS KM2 ON KM1.ID=KM2.ID
GROUP BY KM2.GENERATEDCATS
ORDER BY Count DESC
传奇:

  

INCIDENTSM1 - 售票表
  KMDOCUMENTM1 - 物品表
  KMDOCUMENTA2 - 类别(与主表分开)
  GENERATEDCATS - 类别列

是否可以将所有这些“类别”行合并为一个总计数?

1 个答案:

答案 0 :(得分:3)

尝试GROUP BY提取的类别名称:

SELECT CASE
          WHEN CHARINDEX(' >',SUBSTRING(KM2.GENERATEDCATS,16,20))=0 
          THEN SUBSTRING(KM2.GENERATEDCATS,16,20) 
          ELSE SUBSTRING(SUBSTRING(KM2.GENERATEDCATS,16,20),1,
                         CHARINDEX(' >',SUBSTRING(KM2.GENERATEDCATS,16,20)))
       END AS "Final",
COUNT(KM2.GENERATEDCATS) AS "Count"    
FROM INCIDENTSM1 AS SD 
LEFT JOIN KMDOCUMENTM1 AS KM1 ON SD.CBA_KPF_ID=KM1.ID
LEFT JOIN KMDOCUMENTA2 AS KM2 ON KM1.ID=KM2.ID
GROUP BY CASE
            WHEN CHARINDEX(' >',SUBSTRING(KM2.GENERATEDCATS,16,20))=0 
            THEN SUBSTRING(KM2.GENERATEDCATS,16,20) 
            ELSE SUBSTRING(SUBSTRING(KM2.GENERATEDCATS,16,20),1,CHARINDEX(' >',
                           SUBSTRING(KM2.GENERATEDCATS,16,20)))
         END
ORDER BY Count DESC