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

问题描述 投票:0回答:3

我想基于表中其他列的值创建一个包含50%,60%等值的新列。从下面显示的输出中,我想根据'cnt'列中的值得到'Desired Results'列。目前我的输入数据如下所示

enter image description here

我只能从下面的查询中获取记录的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

我想输出如下所示

enter image description here

sql postgresql group-by percentage
3个回答
1
投票

使用窗口功能: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;

0
投票

为此,您可以有两个子查询,其中一个按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

0
投票

您可以使用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
© www.soinside.com 2019 - 2024. All rights reserved.