我正在尝试生成一份报告,显示每个零件编号的这些零件的测试结果,包括通过和失败的数量,以及通过和失败的百分比。
到目前为止,我有以下内容:
SELECT r2.PartNo, [Pass] AS Passed, [Fail] as Failed
FROM
(SELECT ResultID, PartNo, Result FROM Results) r1
PIVOT (Count(ResultID) FOR Result IN ([Pass], [Fail])) AS r2
ORDER By r2.PartNo
这是解决方案的一半(通过和失败的总数);问题是,我如何推动并包括百分比?
我还没有尝试过,但我想我可以从头开始,并建立一系列子查询,但这更像是一个学习练习 - 我想知道“最好”(最优雅或最有效)的解决方案,所以我想我会寻求建议。
我可以扩展这个 PIVOT 查询,还是应该采取不同的方法?
DDL:
CREATE TABLE RESULTS (
[ResultID] [int] NOT NULL,
[SerialNo] [int] NOT NULL,
[PartNo] [varchar](10) NOT NULL,
[Result] [varchar](10) NOT NULL);
DML:
INSERT INTO Results VALUES (1, '100', 'ABC', 'Pass')
INSERT INTO Results VALUES (2, '101', 'DEF', 'Pass')
INSERT INTO Results VALUES (3, '100', 'ABC', 'Fail')
INSERT INTO Results VALUES (4, '102', 'DEF', 'Pass')
INSERT INTO Results VALUES (5, '102', 'DEF', 'Pass')
INSERT INTO Results VALUES (6, '102', 'DEF', 'Fail')
INSERT INTO Results VALUES (7, '101', 'DEF', 'Fail')
更新:
根据bluefeet的回答,我的解决方案是:
SELECT r2.PartNo,
[Pass] AS Passed,
[Fail] as Failed,
ROUND(([Fail] / CAST(([Pass] + [Fail]) AS REAL)) * 100, 2) AS PercentFailed
FROM
(SELECT ResultID, PartNo, Result FROM Results) r1
PIVOT (Count(ResultID) FOR Result IN ([Pass], [Fail])) AS r2
ORDER By r2.PartNo
我已经将 FLOAT 舍入(而不是 CAST 到 DECIMAL 两次),因为它的效率更高一点,而且我还决定我们只需要失败 %age。