Many a times, you may want to do a count in SQL Server, based on a condition. The easiest way is to use a combination of SUM and CASE as shown in this example
Here’s the same query to try out
DECLARE @TT Table (
CourseID int, StudentID int, EnrolledBy varchar(25)
INSERT INTO @TT
SELECT 1, 1, 'Hrishi' UNION ALL
SELECT 1, 2, 'Sagar' UNION ALL
SELECT 1, 3, 'Tony' UNION ALL
SELECT 1, 2, 'James' UNION ALL
SELECT 1, 4, 'Krish' UNION ALL
SELECT 2, 5, 'Tony' UNION ALL
SELECT 2, 5, 'Molly' UNION ALL
SELECT 2, 6, 'Tony'
COUNT(*) as 'Total Enrolled',
WHEN EnrolledBy = 'Tony'
THEN 1 ELSE 0 END) as 'EnrolledbyTony'
In the query shown above, we are using SUM and CASE to count data only for those records, which are Enrolled by Tony. Similarly instead of SUM, you can also use COUNT which only counts the non-null values.
Did you like this post?
|subscribe via rss||subscribe via e-mail|
|print this post||follow me on twitter|