78

Does anyone know how can I do a count in SQL Server based on condition.

Example:

How can I do a column count for records with name 'system', and total CaseID records in the table?

Customer table

UserID     CaseID     Name
1          100        alan
1          101        alan
1          102        amy
1          103        system
1          104        ken
1          105        ken
1          106        system  

The result will display like below:

UserID    TotalCaseID    TotalRecordsWithSystem
1         7              2
1
  • Why should you not use WHERE name = 'system'? Commented Nov 7, 2017 at 23:50

4 Answers 4

163

Use SUM/CASE...

SELECT
    COUNT(*),  --total
    SUM(CASE WHEN name = 'system' THEN 1 ELSE 0 END) --conditional
FROM
    myTable
Sign up to request clarification or add additional context in comments.

4 Comments

Oh the old good SUM CASE... Always so helpful, always so easy to forget about. Thank you!
ELSE 0 END doesn't work for me. I have to use ELSE null END as per @kage 's answer
@SebastianJ. probably because you used COUNT() on the CASE WHEN .. THEN .. ELSE .. END construction. If you use SUM() as shown it will work just fine.
SELECT COUNT(*) FROM myTable WHERE name='system' works too, no need for CASE WHEN
17

I think he wanted user id in the results

SELECT 
    userid,
    COUNT(*) as TotalcaseID, --total 
    SUM(CASE WHEN name = 'system' THEN 1 ELSE 0 END) as TotalRecordsWithSystem  
FROM 
    myTable 
group by userid

1 Comment

At that, example output shows TotalCaseID, too.
9
select
userid,
count('x') as TotalCaseID,
count(case when name = 'system' then 'x' else null end) as TotalRecordsWithSystem
from CustomerTable
group by userid

Comments

9

If you're on SQL Server 2012+, then you can use SUM/IIF

SELECT
    COUNT(*) AS Total,
    SUM(IIF(Name = 'system', 1, 0)) AS SystemTotal
FROM
    CustomerTable

Comments

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.