sql - How to get count and use that count in a calculation with out nested query?
问题描述
I'm trying to get a count and a rate using that count. Every query I've tried that does not used a nested query gives me a grouping error as the tuple that uses the count in the calculation cannot be in the group by expression.
The query below gets me the data I'm looking for. Is there a way to write this query as a single select with out the nested query?
select
org,
format_number(distinct_preg,0),
format_number(total_patients,0),
format_number((distinct_preg/total_patients * 100),2) preg_rate
from (
select
preg.org,
count(distinct preg.patient_id) distinct_preg,
tot.total_patients total_patients
from
pregnancy preg
join (
select org, count(distinct patient_id) total_patients from enc group by 1
) tot on preg.org = tot.org
group by 1,3
)
order by 1
--- UPDATE ----------------------------
This seems to have something to do with the format_number() function.
This query works:
select
preg.org,
format_number(count(distinct preg.patient_id),0) distinct_preg,
tot.total_patients total_patients,
format_number((count(distinct preg.patient_id) / tot.total_patients * 100),2) preg_rate
from
pregnancy preg
join (
select org, count(distinct patient_id) total_patients from enc group by 1
) tot on preg.org = tot.org
group by 1,3
This one gives the error shown and differs only by the format call:
select
preg.org,
format_number(count(distinct preg.patient_id),0) distinct_preg,
format_number(tot.total_patients,0) total_patients,
format_number((count(distinct preg.patient_id) / tot.total_patients * 100),2) preg_rate
from
pregnancy preg
join (
select org, count(distinct patient_id) total_patients from enc group by 1
) tot on preg.org = tot.org
group by 1,3
解决方案
If you want the average number of pregnancies per patient, you can use:
select org, count(*) as num_pregnancies, count(distinct patient_id) as num_patients,
count(*) * 1.0 / count(distinct patient_id) as avg_pregnancies_per_patient
from pregnancies p
group by org;
Without a clear explanation of what you are trying to do, this is a bit of speculation. However, it seems like a very reasonable metric and one you are attempting to calculate.
推荐阅读
- python-3.x - 关于 scipy.stats.randint 中 rvs 边界的问题
- javascript - 如何在屏幕外使用反应导航
- go - 为什么没有检测到 Go?
- r - 如何使用 R 创建维恩图?
- react-native - undefined 不是对象(评估 '_effects.buffers.expanding')
- java - 如何将数据与复制和克隆等其他方法一起处理成 CSV 文件?
- reactjs - 开玩笑:setTimeout 被调用了太多次
- arrays - 这是什么意思:项目:数组
- java - 修改列表内对象数据成员的文本
- c++ - 如何放大 Mandelbrot Set 中的光标点?