如何计算sql oracle中带条件使用的百分比?

os8fio9y  于 2023-03-17  发布在  Oracle
关注(0)|答案(2)|浏览(192)

我有一张table看起来有点像这个。
| 类型|人数|
| - ------|- ------|
| 项目a|1个|
| 项目a|无|
| 项目a|1个|
| 项目a|1个|
| B|无|
| B|1个|
| (c)秘书长的报告|1个|
| (c)秘书长的报告|1个|
我需要计算大于10%的每种类型的零的百分比,所以结果必须如下所示:
| 类型|占0的百分比|
| - ------|- ------|
| 项目a|二十五|
| B|五十|

5lwkijsr

5lwkijsr1#

使用条件聚合:

SELECT type,
       COUNT(CASE value WHEN 0 THEN 1 END) / COUNT(*) * 100 AS percentage_of_0
FROM   table_name
GROUP BY type

其中,对于示例数据:

CREATE TABLE table_name (type, value) AS
SELECT 'a', 1 FROM DUAL UNION ALL
SELECT 'a', 0 FROM DUAL UNION ALL
SELECT 'a', 1 FROM DUAL UNION ALL
SELECT 'a', 1 FROM DUAL UNION ALL
SELECT 'b', 0 FROM DUAL UNION ALL
SELECT 'b', 1 FROM DUAL UNION ALL
SELECT 'c', 1 FROM DUAL UNION ALL
SELECT 'c', 1 FROM DUAL;

输出:
| 类型|占0的百分比|
| - ------|- ------|
| B|五十|
| (c)秘书长的报告|无|
| 项目a|二十五|
fiddle

u1ehiz5o

u1ehiz5o2#

如果01是仅有的两个可能的值,则可以使用聚合和算术,如下所示:

select type, avg(1 - number) * 100 as percentage_of_0s
from mytable t
group by type

如果有更多可能的值,并且您需要0值的百分比,那么我建议使用avg()case表达式:

select type, 
    avg(case when number = 0 then 100 else 0 end) as percentage_of_0s
from mytable t
group by type

相关问题