如何划分两个select查询结果并计算百分比

How to divide two select query results and calculate the percentage

我有以下 2 select 个查询。我想将第一个 select 查询结果除以第二个 select 查询结果,然后将此结果乘以 100 以计算百分比。但是不知道怎么做。

select count(*) from rate_errors where id > to_char(SYSTIMESTAMP - INTERVAL '1' HOUR,'YYYYMMDDHH24MISS')||'0000'

select count(*) from SDR_O2 where id > to_char(SYSTIMESTAMP - INTERVAL '1' HOUR,'YYYYMMDDHH24MISS')||'0000'
with x as 
(select count(*) rcnt from rate_errors where id > to_char(SYSTIMESTAMP - INTERVAL '1' HOUR,'YYYYMMDDHH24MISS')||'0000')
, y as (select count(*) scnt from SDR_O2 where id > to_char(SYSTIMESTAMP - INTERVAL '1' HOUR,'YYYYMMDDHH24MISS')||'0000')
select 100*rcnt/scnt from x, y;

您可以使用 cte 来完成此操作。但是,如果上面的x和y之间不存在任何关系,则无法确定结果。

我倾向于使用 cross join:

select r.cnt / o.cnt
from (select count(*) as cnt
      from rate_errors
      where id > to_char(SYSTIMESTAMP - INTERVAL '1' HOUR, 'YYYYMMDDHH24MISS') ||'0000'
     ) r cross join
     (select count(*) as cnt
      from SDR_O2
      where id > to_char(SYSTIMESTAMP - INTERVAL '1' HOUR, 'YYYYMMDDHH24MISS')||'0000'
    ) o;

如果需要,您可以将 id 计算分解为 CTE:

with params as (
      select to_char(SYSTIMESTAMP - INTERVAL '1' HOUR, 'YYYYMMDDHH24MISS')||'0000'
      from dual
     )
select r.cnt / o.cnt
from (select count(*) as cnt
      from params cross join rate_errors re
      where re.id > params.id
     ) r cross join
     (select count(*) as cnt
      from params cross join SDR_O2 o
      where o.id > params.id
    ) o;

这样可以更轻松地更改 id 并确保两个子查询的逻辑相同。