我想通过Postgresql创建一些汇总统计数据并在我的数据中实现控制结构。我正在使用分组依据。问题是我不希望在“选择”子句中显示列,但group by子句会强制我也使用该列
我已经尝试使用下面的代码,但是不幸的是,我不想按“ Valuenum”分组。但是,我想利用该列创建一个新列(within_range),如下面的查询所示。我的实际数据如下图所示。请注意,这只是一个示例。 subject_id可能会重复使用不同的hadm_ids
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_id以及每个患者及其各自hadm_ids下的记录数(记录总数,范围内)分组
答案 0 :(得分:0)
您不能在group by中使用别名,而必须直接在group by中使用别名,或者必须使用子查询或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