每个科目的教师和学生人数

时间:2016-03-08 10:19:18

标签: php sql

我有3个表格,user_table分类为教师或学生,subject_table提及不同的主题,enrolled_table说明谁注册为教师/学生以及哪个主题。< / p>

我想要计算每个科目的学生,老师数量!

USER_TABLE

user_id | user_name | contact_no | password | flag
      6 | Abhis     |  123456788 |      123 | s
      5 | Abhish    |  123456789 |      123 | s
      8 | Sneha     | 1111111111 |      123 | s
      7 | Snehil    | 1111112222 |      123 | s
      1 | Narsingh  | 1234567890 |      123 | t
      2 | Abhinav   | 1234567891 |     1234 | t
      3 | Abhi      | 1234567892 |      123 | s
      4 | Abhishek  | 1234567893 |      123 | s  

subject_table

sub_id | sub_name 
     3 | CSS
     1 | HTML
     2 | JQUERY

enrolled_table

enr_id | sub_id | user_id | date       | start_time | end_time
     1 |      1 |       1 | 2016-04-01 | 09:00:00   | 10:00:00
     2 |      2 |       1 | 2016-04-01 | 10:00:00   | 11:00:00
     3 |      3 |       1 | 2016-04-01 | 11:00:00   | 12:00:00
     4 |      1 |       5 | 2016-04-01 | 09:00:00   | 10:00:00
     5 |      1 |       6 | 2016-04-01 | 12:00:00   | 13:00:00
     6 |      1 |       7 | 2016-04-01 | 12:00:00   | 13:00:00
     7 |      1 |       2 | 2016-04-01 | 13:00:00   | 14:00:00
     8 |      2 |       2 | 2016-04-01 | 13:00:00   | 14:00:00

1 个答案:

答案 0 :(得分:1)

SELECT
    st.sub_name,
    COUNT(CASE WHEN ut.flag = 's' THEN 1 END) AS students,
    COUNT(CASE WHEN ut.flag = 't' THEN 1 END) AS teachers
FROM
    subject_table st
    INNER JOIN enrolled_table et ON et.sub_id = st.sub_id
    INNER JOIN user_table ut ON ut.user_id = et.user_id
GROUP BY
    st.sub_name