簡體   English   中英

兩個選擇語句之間的數學運算

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM