多个GROUP BY列成一列

时间:2010-09-02 16:49:57

标签: sql sql-server count group-by

产品按约20个标准分组进行检查和通过/失败。 他们想要一份报告,计算每个组中每个缺陷的数量。

缺陷*是varchar(3),用于识别哪些标准失败 该表有3列缺陷,我可以用以下内容返回它们:

SELECT GroupID,
    Defect1, COUNT(Defect1) as Occ1,
    Defect2, COUNT(Defect2) as Occ2,
    Defect3, COUNT(Defect3) as Occ3
FROM Product
WHERE Run = 1728 AND Defect1 IS NOT NULL
GROUP BY GroupID, Defect1, Defect2, Defect3
ORDER BY GroupID

其中输出如下:

GroupID Def1    Occ1    Def2    Occ2    Def3    Occ3
RF-061   CPP       1     FPV       1    null       0
RF-061   FPV       1     CPP       1    null       0
RF-061   HCR       1     CHP       1    null       0
RF-061   CHP       1     FPV       1    null       0
RF-061   FBL       1     HCR       1     FPT       1
RF-061   CHP       1     CPP       1     HCR       1
RF-061   CHP       1     CPP       1    null       0
RF-061   CPP       1     FBL       1    null       0
...

期望的输出:

GrPupID Def Occurrences
BF-061  FPV 4
BF-061  CPP 5
BF-061  CHP 5
BF-061  HCR 5
BF-061  FBL 3
BF-061  PPC 1
BF-061  FPT 1

在SQL Server 7上,是的,我知道。

2 个答案:

答案 0 :(得分:5)

您可以使用视图来模拟1NF表,然后它会很简单。

CREATE VIEW tempView
AS
SELECT GroupID, Defect1 AS Defect, Run 
FROM Product
UNION ALL
SELECT GroupID, Defect2 AS Defect, Run 
FROM Product
UNION ALL
SELECT GroupID, Defect3 AS Defect, Run 
FROM Product

GO

SELECT GroupID, Defect, COUNT(*) AS Occurrences
FROM tempView
WHERE Run = 1728 
GROUP BY GroupID, Defect
ORDER BY GroupID

答案 1 :(得分:0)

对于SQL Server 2005/2008,请使用UNPIVOT函数。
我没有测试,所以考虑伪代码:
SELECT GroupID,DefectType,COUNT(*)AS出现次数

- 建造桌子 --GroupID缺陷缺陷类型
--RF-061 Defect1 CPP
--RF-061 Defect1 FPV
--.............

SELECT GroupID,Defect,DefectType
来自 (SELECT GroupID,Defect1,Defect2,Defect3
   从产品)p
UNPIVOT
   (DefectType FOR缺陷IN(缺陷1,缺陷2,缺陷3)
   )AS unpvt
)x