Sql 两个select语句之间的数学运算

Sql 两个select语句之间的数学运算,sql,postgresql,Sql,Postgresql,我目前正试图在我的postgres db中找到一定数量的预注册用户的百分比,操作将是(1185*100)/3104=38.17。为此,我使用两个select语句来检索每个计数,但我无法在它们之间进行操作: + count + - 1185 - - 3104 - 这就是我所拥有的: select count(*) from crm_user_preregistred left join crm_player on crm_user_preregistred."

我目前正试图在我的postgres db中找到一定数量的预注册用户的百分比,操作将是
(1185*100)/3104=38.17
。为此,我使用两个select语句来检索每个计数,但我无法在它们之间进行操作:

+ count +
-  1185 -
-  3104 -
这就是我所拥有的:

select
    count(*)
    from crm_user_preregistred
    left join crm_player on crm_user_preregistred."document" = crm_player."document" 
    left join crm_user on crm_player.user_id = crm_user.id
    where crm_user.email is not null
union all
select
    count(*)
    from crm_user_preregistred

提前感谢您提供的任何提示或帮助。

您可以使用一些with子句简化您的选择,用count(*)选择替换值,可能对结果进行一些格式化,并在value2上检查0

with temp_value1 as (
   select 1185 as value1 ),
temp_value2 as (
select 3104 as value2 )

select (select temp_value1.value1::float * 100  from temp_value1) /
(select temp_value2.value2::float from temp_value2)
结果: 38.17654639175258

通过您的选择:

with temp_value1 as (
select
    count(*) as value1
    from crm_user_preregistred
    left join crm_player on crm_user_preregistred."document" = crm_player."document" 
    left join crm_user on crm_player.user_id = crm_user.id
    where crm_user.email is not null
),
temp_value2 as (
select
    count(*) as value2
    from crm_user_preregistred
)

select (select temp_value1.value1::float * 100  from temp_value1)  / (select temp_value2.value2::float from temp_value2)

您可以在一个查询中执行此操作:

select count(*) filter (where cu.email is not null) * 100.0 / max(cup.cnt)
from (select cup.*, count(*) over () as cnt
      from crm_user_preregistred cup
     ) cup left join
     crm_player cp
     on cup."document" = cp."document" left join
     crm_user cu
     on cp.user_id = cu.id
where cu.email is not null;
我怀疑查询可以进一步简化,但在不了解数据模型的情况下,很难提出具体建议