我有一个像
这样的查询select count(1) from table_a where state=1;
它给出20
select count(1) from table_a where state in (1,2);
它给出25
我想查询提取百分比80%(将是20 * 100/25)。 可以只在一个查询中使用这些吗?
答案 0 :(得分:1)
我认为没有测试以下SQL命令可以做到这一点
SELECT SUM(CASE WHEN STATE = 1 THEN 1 ELSE 0 END)
/SUM(CASE WHEN STATE IN (1,2) THEN 1 ELSE 0 END)
as PERCENTAGE
FROM TABLE_A
或以下
SELECT S1 / (S1 + S2) as S1_PERCENTAGE
FROM
(
SELECT SUM(CASE WHEN STATE = 1 THEN 1 ELSE 0 END) as S1
,SUM(CASE WHEN STATE = 2 THEN 1 ELSE 0 END) as S2
FROM TABLE_A
)
或以下
SELECT S1 / T as S1_PERCENTAGE
FROM
(
SELECT SUM(CASE WHEN STATE = 1 THEN 1 ELSE 0 END) as S1
,SUM(CASE WHEN STATE IN (1,2) THEN 1 ELSE 0 END) as T
FROM TABLE_A
)
您可以选择性能或可读性!
答案 1 :(得分:1)
正如@ schlebe的第一个查询略有不同,您可以通过制作条件继续使用count()
:
select count(case when state = 1 then state end)
/ count(case when state in (1, 2) then state end) as result
from table_a
或乘以100得到百分比而不是小数:
select 100 * count(case when state = 1 then state end)
/ count(case when state in (1,2) then state end) as percentage
from table_a
Count忽略空值,如果不满足条件,则两个case表达式默认为null(你可以else null
使其显式化)。
使用CTE进行虚拟数据的快速演示:
with table_a(state) as (
select 1 from dual connect by level <= 20
union all select 2 from dual connect by level <= 5
union all select 3 from dual connect by level <= 42
)
select 100 * count(case when state = 1 then state end)
/ count(case when state in (1,2) then state end) as percentage
from table_a;
PERCENTAGE
----------
80
答案 2 :(得分:0)
为什么是plsql标签?无论如何,我认为你需要的是:
(select count(1) from table_a where state=1) * 100 / (select count(1) from table_a where state in (1,2)) from dual