SQL Group没有返回准确的答案

时间:2017-04-05 09:47:25

标签: sql

enter image description here这是当前结果

    select cat.sms_schoolcategoryid as categoryId, 
           cat.sms_name as category , 
           count(sch.sms_name) as schoolname, 
           count(stu.accountnumber)NoofStudent
      from Filteredsms_schoolcategory cat 
inner join Filteredsms_school sch
        on cat.sms_schoolcategoryid=sch.sms_schoolcategoryid
inner join FilteredAccount stu
        on sch.sms_schoolid=stu.sms_schoolid
  group by cat.sms_schoolcategoryid, 
           cat.sms_name 
         ;

我有三张桌子,一张是分类,第二张是学校,第三张是学生。我只想在我加入表类别和学校时代表学校计算学校它会给我准确的结果,当我加入学生表与学校表时,它会给我错误的结果。请指导我如何做到这一点。

3 个答案:

答案 0 :(得分:0)

除非您提供有关数据模型的更多信息,否则会涉及猜测。但是,您的问题似乎根源于以下内容:

当您加入学生表时,对于学校类别和学校(*)的每个组合,您将生成其他记录。即,你的sql不再按学校类别计算学校,而是学生。

有关具体解决方案和好建议,请参阅@ Nick.McDermaid的评论。

答案 1 :(得分:0)

试试这个

 select count(stu.accountnumber) as NoofStudent
       , catsch.categoryId
       , catsch.category
       , catsch.schoolname
 from FilteredAccount stu
 inner join (
     select cat.sms_schoolcategoryid as categoryId
        , cat.sms_name as category 
        , count(sch.sms_name) as schoolname
        , sch.sms_schoolid 
     from Filteredsms_schoolcategory cat 
       inner join Filteredsms_school sch
        on cat.sms_schoolcategoryid = sch.sms_schoolcategoryid
     group by cat.sms_schoolcategoryid, cat.sms_name, sch.sms_schoolid) catsch

  on catsch.sms_schoolid = stu.sms_schoolid

 group catsch.categoryId
       , catsch.category
       , catsch.schoolname

答案 2 :(得分:0)

count()返回非NULL值的数量。因此,您的两个count()将返回相同的值。您可以使用count(distinct)快速修复查询:

select cat.sms_schoolcategoryid as categoryId, 
       cat.sms_name as category , 
       count(distinct sch.sms_name) as schoolname, 
       count(distinct stu.accountnumber) as NoofStudent
from Filteredsms_schoolcategory cat inner join
     Filteredsms_school sch
     on cat.sms_schoolcategoryid = sch.sms_schoolcategoryid inner join
     FilteredAccount stu
     on sch.sms_schoolid = stu.sms_schoolid
group by cat.sms_schoolcategoryid, cat.sms_name ;

实际上,你可能不需要第二次计数。只需count(stu.accountnumber)就可以算上学生。