views:

58

answers:

3

Here's the scenario:

I have a table with 3 columns: 'KeyColumn', 'SubKeyColumn' and 'BooleanColumn', where the first two are the primary keys of the table.

For my query, I'd like to count the number of rows there are for any given value in 'KeyColumn', and I'd also like to know which ones have a value of true for 'BooleanColumn'. My initial thought was to create a query like this:

SELECT
   COUNT(*)
   ,COUNT(CASE WHEN BooleanColumn = 1 THEN 1 ELSE 0 END)
FROM
   MyTable
GROUP BY
   KeyColumn

However, the 2nd part does not work (I'm not entirely sure why I thought it would to begin with). Is it possible to do something like this in one query? Or am I going to need to do multiple queries to make this happen?

+3  A: 

Change COUNT to SUM in the 2nd part. ;)

Phil Sandler
Nice. Well that was easy... today is not my day.Thanks!
John
pretty much what i was going to say.
DForck42
+2  A: 

... CASE WHEN BooleanColumn = 1 THEN 1 ELSE NULL END ...

COUNT counts the NON-NULL rows.

I see; I guess it helps when you know what count() is actually counting!
John
A: 

You could also do SUM(CAST(BooleanColumn AS TINYINT))