按特定数量的列分组但在select子句中排除它们

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

我想通过Postgresql在我的数据中创建一些摘要统计和实现控制结构。我正在使用group by。问题是我不想在“Select”子句中显示一个列,但group by子句强制我也使用该列

我已经尝试使用下面的代码,但不幸的是我不希望按'Valuenum'分组。但是,我想利用该列创建一个新列(within_range),如下面的查询所示。我的实际数据如下所示。请注意,这只是一个样本。 subject_id可能会重复使用不同的hadm_ids

enter image description here

select subject_id,hadm_id,count(*) as "Total no of records",
         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
         order by subject_id,hadm_id

我希望输出就像每个受试者分组的每个主题和每个患者及其各自的hadm_ids下的记录数(记录总数,范围内)

enter image description here

sql postgresql group-by
1个回答
0
投票

您不能在组中使用别名,您必须直接使用组中的一个或您必须使用子查询或cte

select subject_id,hadm_id,count(*) as "Total no of records",
         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,case 
             when valuenum between 80 and 110 then 1
             else 0
             end
         order by subject_id,hadm_id

这是你的代码的cte版本

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 


) select subject_id,hadm_id,within_range,count(*) as cnt
  from cte group by subject_id,hadm_id,within_range
© www.soinside.com 2019 - 2024. All rights reserved.