如何查询结果中遗漏的数据

How to query data that is ommitted from the results

所以我有以下信息

输出

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

select sum(Case when s.diabetic is null then 1 else 0 end) AS notD

除了糖尿病记录之外,我显然一无所获 - 真实状态

我该如何解决这个问题

注意:如果您有更好的问题标题,请提出建议!

您可以尝试使用 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

您可以使用window函数SUM OVER得到学生总数。 Window 函数 运行 作用于你已有的结果,可以说是 post 聚合 :-)

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;

您可以使用条件聚合来显示每所学校一行及其糖尿病发病率:

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 条款,如果您还想查看没有糖尿病患者的学校。