简体   繁体   中英

Get school count and grade count using group by in mysql query

I want to get count for total school with count of total grade included in that school, incase of school count it should not consider duplicate school id . and count of total grade including school 1 and school 2 ,All I want to acheive using single query is it possible to get as mentioned in expected out put.

Table:

school_id      grade

  1             1

  2             1


  1             3

  1             4

Expected output:

1) school count=2

2) grade count for individual school like

    school_id   grade_count

      1           3
      2           1

3)  total grade count  (school 1+school2)=4

I used this Mysql query but it is not working as per requirement to get all three output

Mysql query:

select count(*) as total_school,count(grade) from (SELECT grade FROM schools group by school_id)X 
SELECT 
  `school_id`,
  (SELECT COUNT(DISTINCT `school_id`) FROM `school_grade`) as different_school_count,
  COUNT(*) as school_count,
  COUNT(DISTINCT `grade`) as grade_count,
  (SELECT COUNT(*) FROM `school_grade`) as total_grade_count
FROM
  `school_grade`
GROUP BY `school_id`

OUTPUT:

| school_id | different_school_count | school_count | grade_count | total_grade_count |
|-----------|------------------------|--------------|-------------|-------------------|
|         1 |                      2 |            3 |           3 |                 4 |
|         2 |                      2 |            1 |           1 |                 4 |

http://sqlfiddle.com/#!9/9132c7/16

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM