如何在单个查询中计算百分比的百分比

How to calculate a percentage of a percentage in a single query

使用数据块 SQL 我创建了一个 table 如下所示:

tablename RunDate Quality qaflag Status
blah 2022-06-02 bronze 1 Passed
blah1 2022-06-02 silver -1 failed

我可以编写一个查询来计算 table 中每种质量类型的百分比 e.i.

SELECT Quality, 
       COUNT(Status)*100/(SELECT COUNT(Status) FROM test) as Percentage
FROM test
GROUP BY Quality 

这将给我这个输出:

Quality PercentageTotal
Silver 64
Gold 3
Bronze 33

我还想添加通过或未通过的每种质量的百分比。 基本上,我需要尝试让它看起来像这样:

Quality PercentageTotal PercentagePassed PercentageFailed
Silver 64 99 1
Gold 3 87 3
Bronze 33 60 40

table 说的是: Silver Tables 占所有 table 测试的 64%,其中 99% 通过,1% 失败。 (其他的依此类推)

我一直在试图弄清楚如何计算 PercentagePassed/Failed 谁能帮忙?

切换到带有 distinct 的 window 函数以消除您的 group by 需求,然后使用 case 表达式:

SELECT distinct Quality
    , count(Status) over (partition by Quality) * 100 / count(status) over (partition by null) PercentageTotal
    , count(case when Status = 'Passed' then 1 end) over (partition by Quality) * 100 / count(status) over (partition by Quality) PercentagePassed
    , count(case when Status = 'Failed' then 1 end) over (partition by Quality) * 100 / count(status) over (partition by Quality) PercentageFailed
FROM test

您可能想考虑切换到另一种支持小数的数据类型,但我已将其保留为您的示例。