Skip to content
Advertisement

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. To do that I’m using two select statements to retrieve each count, but I’ve been unable to operate between them:

+ 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.

Advertisement

Answer

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 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

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)
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement