2

I'm trying to use two identical aggregate function is SQL Server, where I use COUNT(A) with some condition and COUNT(A) with another condition.

For example I want to count all students enrolled in the course ABC, and the second count I want to count all students who have grade A and have enrolled in the same course ABC.

But the result of the COUNT will be on the same table but on different column, is it possible to do this and how can I implement it. Thanks.

enter image description here

enter image description here

And I want the resulting table

enter image description here

2
  • please provide some sample data with your desired output in tabular format Commented Oct 31, 2020 at 4:21
  • Few quick things would be helpful. Firstly, you tagged sql-server in the question but as per your question it is MySQL. They are different Databases, so would suggest to update the tag. Secondly, if you can provide sample input & output datasets, it will help us to provide an answer faster. Commented Oct 31, 2020 at 4:21

1 Answer 1

3

Use conditional aggregation

select name, count(*) as all_student,
       count(case when grade='A' then 1 end) as cnt_A,
       count(case when grade='B' then 1 end) as cnt_B
from course_table c inner join student_table s on c.name=s.course
group by name
Sign up to request clarification or add additional context in comments.

2 Comments

okay thankyou very much, i've tried it and it work. Thanks @fahmi
@mtirtapradja, happyy to help you. Please don't forget to mark it as an accepted answer :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.