因此,我经常遇到必须对数据进行分区或分组(逻辑上)然后进行比较的情况。比如:
“某个值出现在组中和不在组中的频率以及它们各自的百分比是多少”
select LESS_THAN, GREATER_THAN, round(LESS_THAN /(LESS_THAN+GREATER_THAN),4) as percentage
from (
select 'less than' as type, level as rn from dual where level <= 5 connect by level <= 10 union
select 'greater than' as type, level as rn from dual where level > 5 connect by level <= 10
)
pivot(
sum(rn)
for type in (
'less than' as LESS_THAN, 'greater than' as GREATER_THAN
)
);
有什么聪明的方法可以简化这类事情吗?
您可以使用条件聚合:
SELECT COUNT(CASE type WHEN 'less than' THEN 1 END) AS less_than,
ROUND(AVG(CASE type WHEN 'less than' THEN 1 ELSE 0 END), 4) AS percentage
FROM table_name
对于样本数据:
CREATE TABLE table_name (type, rn) AS
SELECT CASE
WHEN level <= 5
THEN 'less than'
ELSE 'greater than'
END,
level
FROM DUAL
CONNECT BY LEVEL <= 10;
输出:
少于 | 百分比 |
---|---|
5 | .5 |