Reputation: 287
I have this table that has 2 columns:
ID, TypeID
Each ID can have multiple TypeIDs. In the query result i want to have the following:
ID, Count(TypeID = 10), Count(TypeID = 20 or 30), Count(TypeID 40 and 50)
The query itself should be as fast / performant as possible. Can anyon help?
Upvotes: 1
Views: 125
Reputation: 79969
Try this:
SELECT
ID,
SUM(CASE WHEN TypeID = 10 THEN 1 ELSE 0 END) "Count of 10",
SUM(CASE WHEN TypeID IN (20, 30) THEN 1 ELSE 0 END) "Count of 30 or 20",
SUM(CASE WHEN TypeID IN (40, 50) THEN 1 ELSE 0 END) "Count of 40 AND 50"
FROM Table
GROUP BY ID;
For the last case: Count(TypeID 40 and 50)
I think the predicate TypeID IN (40, 50)
will work for you, since it will give the count of values 40 and 50.
Upvotes: 6