tags:

views:

96

answers:

3

Hi,

If I have a table

AgentID | IsNew | TeamID
1         N       1
2         Y       2
3         Y       2
4         N       2
5         Y       1

I want to return the following from a query:

Team | CountIsNew = N | CountIsNew = Y
1      1                1
2      1                2

Is there a way I can do this?
Using Oracle 10

+8  A: 
SELECT  team, SUM(DECODE(IsNew, 'N', 1, 0)), SUM(DECODE(IsNew, 'Y', 1, 0))
FROM    mytable
GROUP BY
        team
Quassnoi
5/5 - cheers man. I'll go check out decode and see how that works!
Gribbler
@OMGPonies: I prefer `DECODE` for such grouping queries since it's `NULL`-aware. `DECODE(NULL, NULL, 1, 0)` returns `1`, `CASE NULL WHEN NULL THEN 1 ELSE 0 END` returns `0`. You can just substitute the `NULL` as any other regular value.
Quassnoi
am I right in saying that DECODE is oracle specific while Dirk's answer would work for any database?
Gribbler
@Gribbler: yes.
Quassnoi
+5  A: 
SELECT TeamId
     , SUM(CASE WHEN IsNew = 'N' THEN 1 ELSE 0 END) AS CountIsNotNew
     , SUM(CASE WHEN IsNew = 'Y' THEN 1 ELSE 0 END) AS CountIsNew
FROM Agent
GROUP BY TeamId
Dirk
A: 

Yet another way - COUNT doesn't count NULLs (except for COUNT(*)):

SELECT TeamId,
       COUNT(DECODE(IsNew,'N',1)) CountIsNotNew,
       COUNT(DECODE(IsNew,'Y',1)) CountIsNew
FROM Agent
GROUP BY TeamId;

Or, if you prefer CASE:

SELECT TeamId,
       COUNT(CASE IsNew WHEN 'N' THEN 1 END) CountIsNotNew,
       COUNT(CASE IsNew WHEN 'Y' THEN 1 END) CountIsNew
FROM Agent
GROUP BY TeamId;

(note: the "1"s could be any literal value)

Jeffrey Kemp