LEFT Joint Aggregate中的SQL计数?

时间:2017-04-23 01:30:55

标签: mysql sql database

我有四张桌子,如下图enter image description here

我想计算有多少状态&#39; <&#39; 的学生表格提交的提交类型&#39; 1&#39;并按 student_id 分组,所以在最后我可以得到这样的表enter image description here

我已经尝试过像这样的SQL查询

select p.id, (SELECT count(*) FROM  (select b.id from student as a , submission  as b WHERE a.id = b.student_id and b.id_submission_type =1  and a.status_n='v' and a.id_academic_programe = p.id GROUP BY b.student_id) )  from academic_programe as p

但是给我错误

  

1054 - 未知栏&#39; p.id&#39;在&#39; where子句&#39;

有什么建议吗? sory for my english

3 个答案:

答案 0 :(得分:1)

关联不能在嵌套子查询中。幸运的是,这很容易解决:

select p.id,
       (select count(*)
        from student st join
             submission su 
             on st.id = su.student_id and
                su.id_submission_type = 1 and
                st.status_n = 'v' and
        where st.id_academic_programe = p.id
       )
from academic_programe p;

答案 1 :(得分:1)

试试这个:

select c.academic_program_name,count(a.distinct student_name) as count
from
(select * from student where status = 'v') a
inner join
(select * from submission id_submission_type=1) b
on a.id  =b.student_id
inner join
academic_program_name c
on a.id_academic_programe = c.id
group by c.academic_program_name;  

如有任何疑问,请与我联系。

答案 2 :(得分:1)

请尝试以下方法......

SELECT student.id,
       student_name,
       academic_program_name AS Programe,
       COUNT( status_n ) AS status_n_count
FROM student
JOIN Submission ON student.id = Submission.student_id
RIGHT JOIN academic_program ON student.id_academic_programe = academic_program.id
WHERE id_submission_type = 1
  AND status_n = 'v'
GROUP BY student.id,
         student_name,
         academic_program_name;

此声明首先加入studentSubmission,以便获得包含student idstudent_name的表格, status_nid_submission_type个字段。然后RIGHT JOIN形成一个表格,其中列出每个学术课程以及每个学生的详细信息,并且仍然列出没有学生的课程。

结果数据集根据您的条件使用WHERE子句GROUP ed和SELECT ed

进行优化

如果您有任何问题或意见,请随时发表评论。