简体   繁体   中英

How to count the number of occurrences of a specific value in a column in SQL without doing two SQL calls

I have a table: Judges (JName char(25), LawSchool char(25)).

I'm trying to retrieve the number of judges that attended Harvard and the number of Judges that attended Yale in one SQL Call. I know that I could do this

SQL CALL 1)

select LawSchool, count(*) as cnt from Judges where LawSchool = 'Harvard'

SQL CALL 2)

select LawSchool, count(*) as cnt from Judges where LawSchool = 'Yale'

But is there not a way I can retrieve the number of Judges who attended Yale and the number of judges who attended Harvard in one SQL call but store them in two variables such as cnt and cnt2?

select LawSchool, count(*) as cnt 
 from Judges 
 where LawSchool in ('Harvard','Yale')
 Group By LawSchool

You can use a group by clause to separate the aggregate result per unique value:

SELECT   LawSchool, COUNT(*)
FROM     Judges
WHERE    LawSchool IN ('Harvard', 'Yale')
GROUP BY LawSchool

You can use in and group by

select LawSchool, count(*) as cnt 
from Judges where LawSchool in ( 'Harvard', 'Yale')
group by LawSchool

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