[英]getting the difference between two rows and perform mathematical operation on the difference mysql
[英]mathematical operation between two select statements
我目前正在尝试在我的 postgres 数据库中找到一定数量的预注册用户的百分比,操作将是(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;
我怀疑可以进一步简化查询,但是在不了解您的数据模型的情况下,很难提出具体建议。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.