gpt4 book ai didi

sql - 多个 GROUP BY 列合并为一列

转载 作者:行者123 更新时间:2023-12-04 20:56:16 25 4
gpt4 key购买 nike

产品按大约 20 项标准进行分组以接受检查并通过/未通过。他们想要一份报告,计算单个组中每个缺陷的数量。

Defect* 是 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 上,是的,我知道。

最佳答案

您可以使用 View 来模拟 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

关于sql - 多个 GROUP BY 列合并为一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3629284/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com