我正在尝试将多个条件摘要选择到基于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...

感谢任何帮助。

有帮助吗?

解决方案

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

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

其他提示

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 null”在省略else子句时隐式,因此您也可以放心地将其关闭。

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

这样做。

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 
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top