T-SQL Count rows with specific values (Multiple in one query)

Solution 1:

SELECT IGrp, 
    COUNT(CASE WHEN Value1 > 1 THEN 1 ELSE NULL END) AS V1High, 
    COUNT(CASE WHEN Value2 > 1 THEN 1 ELSE NULL END) AS V2High 
FROM Tbl
GROUP BY IGrp

Solution 2:

You can use the CASE statement:

SELECT IGrp, 
    SUM(CASE WHEN Value1>1 THEN 1 ELSE 0 END) AS V1High, 
    SUM(CASE WHEN Value2>1 THEN 1 ELSE 0 END) AS V2High 
FROM Tbl GROUP BY IGrp 

Solution 3:

make use of case when will do work for you

SELECT IGrp, 
 sum(case when isnull(Value1,0)>1 then 1 else 0 end) AS V1High, 
 sum(case when isnull(Value2,0)>1 then 1 else 0 end) AS V2High 
FROM Tbl GROUP BY IGrp 

Solution 4:

SELECT IGrp, 
    COUNT(CASE WHEN Value1 = 'Foo' THEN 1 ELSE NULL END) AS Tot_Foo, 
    COUNT(CASE WHEN Value1 = 'Blah' THEN 1 ELSE NULL END) AS Tot_Blah 
FROM Tbl
GROUP BY IGrp

This can also be used to compare 2 different values for the same field, with minor changes as shown above.

Very helpful for verifying values that are supposed to exist in a 1:1 ratio.