SQL:PIVOTing Count和;列的百分比

时间:2012-06-20 10:52:06

标签: tsql sql-server-2008-r2 pivot aggregate

我正在尝试制作一份报告,显示每个零件编号,根据传递和失败的数字以及传递和失败的百分比,对这些零件的测试结果。

到目前为止,我有以下内容:

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。

1 个答案:

答案 0 :(得分:4)

听起来你只需要为Percent Passed和Percent Failed添加一列。您可以在PIVOT上计算这些列。

SELECT r2.PartNo
    , [Pass] AS Passed
    , [Fail] as Failed
    , ([Pass] / Cast(([Pass] + [Fail]) as decimal(5, 2))) * 100 as PercentPassed
    , ([Fail] / Cast(([Pass] + [Fail]) as decimal(5, 2))) * 100 as PercentFailed
FROM
(
    SELECT ResultID, PartNo, Result 
    FROM Results
) r1
PIVOT 
(
    Count(ResultID) 
    FOR Result IN ([Pass], [Fail])
) AS r2
ORDER By r2.PartNo