如何返回计数而不计入SQL查询?

时间:2010-04-13 14:41:53

标签: sql oracle select

如果我有桌子

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

我想从查询中返回以下内容:

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

我有办法做到这一点吗? 使用Oracle 10

3 个答案:

答案 0 :(得分:8)

SELECT  team, SUM(DECODE(IsNew, 'N', 1, 0)), SUM(DECODE(IsNew, 'Y', 1, 0))
FROM    mytable
GROUP BY
        team

答案 1 :(得分:5)

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

答案 2 :(得分:0)

另一种方式 - COUNT不计算NULL(COUNT(*)除外):

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

或者,如果您更喜欢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;

(注意:“1”可以是任何字面值)