所以我有以下信息
Diabetic Schools studentcount
false 9010 180
true 9010 3
false 9012 245
true 9012 4
Select s.diabetic as diabetic, sch.buildingid as Schools,
count(distinct s.studentnmr) as Studentcount
from student s
inner join studentschool ss.studentid = s.studentid
inner join school sch.id = ss.schoolid
order by sch.id
Diabetic addresse studentcount calculation
true 9010 3 1,64 %
true 9012 4 1,61 %
计算方式
( sum(diabetic=true)/sum(total number of students of the school) )*100
其他提示
diabeticdate
,其中有一个糖尿病正确的日期。
当我选择
select sum(Case when s.diabetic is null then 1 else 0 end) AS notD
在糖尿病记录旁边,我显然一无所获-真实状态
我该如何解决
注意:如果您对这个问题有更好的标题,请提出建议!
答案 0 :(得分:1)
您可以通过使用over()在下面尝试
with t1 as
(
Select s.diabetic as diabetic, sch.buildingid as Schools,
count(distinct s.studentnmr) as Studentcount
from student s
inner join studentschool ss.studentid = s.studentid
inner join school sch.id = ss.schoolid
order by sch.id
),
t2 as
(
select case when Diabetic='true' then Schools end as addresse,
case when when Diabetic='true' then studentcount end as studentcount,
((case when when Diabetic='true' then studentcount end)::decimal/(sum(studentcount) over())) *100 as calculation
) select * from t2
答案 1 :(得分:1)
您可以使用窗口函数SUM OVER
获取学生总数。窗口函数运行在您已有的结果上,可以说是后期汇总:-)
select
s.diabetic as diabetic,
sch.buildingid as Schools,
count(distinct s.studentnmr) as Studentcount,
count(distinct s.studentnmr)::decimal /
sum(count(distinct s.studentnmr)) over (partition by sch.buildingid) * 100 as rate
from student s
inner join studentschool on ss.studentid = s.studentid
inner join school on sch.id = ss.schoolid
group by sch.buildingid, s.diabetic
order by sch.buildingid, s.diabetic;
答案 2 :(得分:1)
您可以使用条件汇总来显示每所学校的糖尿病发生率:
select
sch.buildingid as Schools,
count(distinct s.studentnmr) as Studentcount
count(distinct case when s.diabetic then s.studentnmr end) as Diabeticcount,
count(distinct case when s.diabetic then s.studentnmr end) /
count(distinct s.studentnmr) * 100 as rate
from student s
inner join studentschool on ss.studentid = s.studentid
inner join school on sch.id = ss.schoolid
group by sch.buildingid
having count(distinct case when s.diabetic then s.studentnmr end) > 0
order by sch.buildingid;
如果您还想查看没有糖尿病的学校,请删除HAVING
子句。