2010-09-02 145 views
3

產品按照大約20個標準進行檢查和合格/不合格。 他們想要一份報告來統計每個團體有多少個每個缺陷。多個GROUP BY列合併爲一列

缺陷*爲varchar(3),用於標識哪些條件失敗。
表有3列缺陷,我可以像回到他們:SQL Server上

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 

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 
... 

所需的輸出7,是的,我知道。

回答

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 
+0

謝謝,這正是我一直在尋找。 – 182764125216 2010-09-02 17:14:04

0

對於SQL Server 2005/2008,請使用UNPIVOT函數。
我沒有測試過,所以考慮爲僞代碼:
SELECT組ID,DefectType,COUNT(*)AS紀錄

--building表
--GroupID缺陷DefectType
--RF-061 Defect1 CPP
--RF-061 Defect1 FPV
--.............

SELECT組ID,缺陷,DefectType
FROM
(SELECT組ID,Defect1,缺陷2,缺陷3
從產品)p
UNPIVOT
(DefectType FOR缺陷(Defect1,Defect2,Defect3)
)AS unpvt
)×

+0

OP在SQL Server 7上! – 2010-09-02 22:52:55

+0

我對這個錯誤表示歉意,聯盟在這種情況下是你的朋友。 – dragos55 2010-09-03 08:34:24