简体   繁体   English

两个选择语句之间的数学运算

[英]mathematical operation between two select statements

I'm currently trying to find the percentage of certain amount of preregistered users in my postgres db, the operation would be (1185 * 100) / 3104 = 38.17 .我目前正在尝试在我的 postgres 数据库中找到一定数量的预注册用户的百分比,操作将是(1185 * 100) / 3104 = 38.17 To do that I'm using two select statements to retrieve each count, but I've been unable to operate between them:为此,我使用了两个 select 语句来检索每个计数,但我一直无法在它们之间进行操作:

+ count +
-  1185 -
-  3104 -

This is what I have:这就是我所拥有的:

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

Thanks in advance for any hint or help.在此先感谢您的任何提示或帮助。

you can use some with clause to simplifie your selects, substitute the values with your count(*) selects, maybe some formating to the result, and a check for 0 on value2你可以使用一些 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)

result : 38.17654639175258结果:38.17654639175258

with your selects:与您的选择:

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)

You can do this in one query:您可以在一个查询中执行此操作:

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;

I suspect that the query could be simplified further, but without knowing your data model, it is hard to make specific suggestions.我怀疑可以进一步简化查询,但是在不了解您的数据模型的情况下,很难提出具体建议。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM