简体   繁体   中英

How to count in a sub-query

So this is the code i have.

SELECT TestName
FROM Testtype
WHERE TestID IN (Select TestID
                    from Tests
                    where Testno IN (Select Testno
                                      from Users
                                      WHERE StudentType= 'StudentType1'
                                      )
                    )

This produces Just a list of the name of the test that matches the Student type so like

Test1
Test2

i am wanting so i can count how many matches for test1 there are so the output is like

No of student that undertook the test   Test Type
52                                      Test1
23                                      Test2

Any help appreciated , thanks.

Replace subqueries with joins, and add GROUP BY :

SELECT tt.TestName, COUNT(*) as NoOfStudents
FROM TestType tt
JOIN Tests t ON tt.TestID=t.TestID 
JOIN Users u ON t.Testno=u.Testno AND u.StudentType= 'StudentType1'
GROUP BY tt.TestName

Youcan use also this query.

SELECT TestName,count(*) StudentsCount
FROM Testtype tt,
     Tests t,
     Users usr
where usr.StudentType='StudentType1'
  and usr.Testno = t.Testno
  and t.TestID=tt.TestID
group by TestName

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