簡體   English   中英

使用PSQL根據其他列中的值生成百分比

[英]Generate percentage from based on values from other column using PSQL

我想基於表中其他列的值創建一個包含50%,60%等值的新列。 從下面顯示的輸出中,我想基於“ cnt”列中的值創建“期望的結果”列。 目前我的輸入數據如下

在此處輸入圖片說明

我只能從下面的查詢中獲取記錄的編號。 但是,我無法生成百分比。 你能幫我么?

with test as
(
select subject_id,hadm_id,case 
             when valuenum between 80 and 110 then 1
             else 0
             end as "within_range"
         from labevents where itemid in ('50809','50931','51529') and 
hadm_id is not null 


) select subject_id,hadm_id,within_range,count(*) as cnt
from test group by subject_id,hadm_id,within_range

我希望輸出如下所示

在此處輸入圖片說明

使用窗口功能: http : //www.postgresqltutorial.com/postgresql-window-function/

with cte as
     (
       select subject_id,
              hadm_id,
              case
                when valuenum between 80 and 110 then 1
                else 0
                end as "within_range"
         from labevents
        where itemid in ('50809', '50931', '51529')
          and hadm_id is not null
     ),
   subq as (
     select subject_id,
            hadm_id,
            within_range,
            count(*) as cnt
       from cte
      group by subject_id, hadm_id, within_range
   ) 
select subq.*, (cnt / sum(cnt) OVER (PARTITION BY subject_id, hadm_id)) * 100 "Desired Results" 
from subq;

為此,您可以有兩個子查詢,其中一個子查詢由hadm_id分組,而另一個子查詢則不是,然后將它們都加入。

select a.* ,(a.cnt/b.cnt)*100 
from(select subject_id,hadm_id,within_range,count(*) as cnt
FROM (select subject_id,hadm_id,case 
             when valuenum between 80 and 110 then 1
             else 0
             end as "within_range"
         from labevents where itemid in ('50809','50931','51529') and 
hadm_id is not null) 
group by subject_id,hadm_id,within_range)a
INNER JOIN
(select subject_id,within_range,count(*) as cnt
FROM (select subject_id,hadm_id,case 
             when valuenum between 80 and 110 then 1
             else 0
             end as "within_range"
         from labevents where itemid in ('50809','50931','51529') and 
hadm_id is not null) 
group by subject_id,within_range)b
on a.subject_id,b.subject_id and a.within_range=b.within_range

您可以將窗口功能與group by 另外,CTE並不是真正必要的,尤其是因為Postgres允許將列別名用於group by

select subject_id, hadm_id,
       (case when valuenum between 80 and 110 then 1
             else 0
        end) as within_range,
       count(*) as cnt,
       count(*) * 100.0 / sum(count(*)) over () as percentage
from labevents
where itemid in ('50809', '50931', '51529') and 
      hadm_id is not null 
group by subject_id, hadm_id, within_range

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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