SQL(DB2)在单个查询中返回多个条件计数

时间:2009-06-19 15:04:39

标签: sql db2

我正在尝试将多个条件摘要选择到基于DB2的数据库上的单个表结果中。

示例:

SELECT COUNT(FOO) FROM T1 WHERE T1.A=1 AS A_COUNT,
SELECT COUNT(FOO) FROM T1 WHERE T1.B=2 AS B_COUNT
Ext...

感谢任何帮助。

4 个答案:

答案 0 :(得分:6)

select count(case when t1.a = 1 then foo else null end) as A_COUNT
     , count(case when t1.b = 2 then foo else null end) as B_COUNT
  from t1
 where t1.a = 1
    or t1.b = 2

Where子句在严格意义上是可选的,但可能有助于表现。当else子句被省略时,“else null”也是隐含的,所以你也可以放心地将其关闭。

答案 1 :(得分:6)

这将计算每个条件的出现次数:

select sum(case when t1.a = 1 then 1 else 0 end) as A_COUNT
     , sum(case when t1.b = 2 then 1 else 0 end) as B_COUNT
  from t1
 where t1.a = 1
    or t1.b = 2

答案 2 :(得分:1)

select count(foo)
  from t1
 where a = 1
union
select count(foo)
  from t1
 where b = 2
....

答案 3 :(得分:0)

这样做。

SELECT  A_COUNT as Type ,COUNT(FOO) FROM T1 WHERE T1.A=1, 

Union


SELECT B_COUNT as Type, COUNT(FOO) FROM T1 WHERE T1.B=2