Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case and Count in SQL Server 2008

I have a table that stores multiple items for a state and I want to get count for every states according to specific conditions. I wrote this query:

SELECT
    State_ID,
    State_Name,
    State_All= CASE WHEN type1=1 AND type2=1 THEN COUNT(Id) END
    State_w= CASE WHEN type1=2 AND type2=1 THEN COUNT(Id) END
    State_s= CASE WHEN type1=2 AND type2=2 THEN COUNT(Id) END
FROM
    tblStates

but I get this Error:

Column 'State_ID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

When I added GROUP BY clause For State_ID,I got above error again for State_Name,and when added State_Name to GROUP BY clause ,I got error for State_All,State_w,State_s.

I don't have a column called State_All,State_w,State_s in my table.

How I can get count according to specific conditions without using CURSORS?

like image 845
Arian Avatar asked Aug 29 '11 06:08

Arian


People also ask

Can you use count in case statement SQL?

CASE can be used in conjunction with SUM to return a count of only those items matching a pre-defined condition. (This is similar to COUNTIF in Excel.) The trick is to return binary results indicating matches, so the "1"s returned for matching entries can be summed for a count of the total number of matches.

What is difference between count (*) and count ID?

Count(*) includes rows with null values whereas count(id) would not include rows with a null id.


2 Answers

You were on the right path.

You put the condition inside the COUNT like this. COUNT ignores NULLs (which is the implied ELSE in the CASE) so you only count true matches. You need the GROUP BY too.

Your error comes from the use of type1 and type2 outside of the COUNT

SELECT
    State_ID,
    State_Name,
    State_All = COUNT(CASE WHEN type1=1 AND type2=1 THEN 1 END), 
    State_w = COUNT(CASE WHEN type1=2 AND type2=1 THEN 1 END), 
    State_s = COUNT(CASE WHEN type1=2 AND type2=2 THEN 1 END)
FROM
    tblStates
GROUP BY
    State_ID, State_Name
like image 110
gbn Avatar answered Nov 15 '22 06:11

gbn


You can change Count to SUM because each record result 1

SELECT
    State_ID,
    State_Name,
    State_All = SUM(CASE WHEN type1=1 AND type2=1 THEN 1 END), 
    State_w = SUM(CASE WHEN type1=2 AND type2=1 THEN 1 END), 
    State_s = SUM(CASE WHEN type1=2 AND type2=2 THEN 1 END)
FROM
    tblStates
GROUP BY
    State_ID, State_Name
like image 42
user3064912 Avatar answered Nov 15 '22 07:11

user3064912