简体   繁体   English

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

[英]SQL (DB2) Return multiple conditional counts in a single query

I am trying select multiple conditional summaries into a single table result on a DB2 based database. 我正在尝试将多个条件摘要选择到基于DB2的数据库上的单个表结果中。

Example: 例:

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...

Any help is appreciated. 任何帮助表示赞赏。

This will count the occurrence of each condition: 这将计算每个条件的发生:

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 clause is optional strictly speaking but may assist performance. Where子句在严格意义上是可选的,但可以帮助表现。 Also "else null" is implicit when the else clause is omitted so you can safely leave that off as well. 当省略else子句时,“else null”也是隐含的,所以你也可以安全地将其关闭。

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

This will do it. 这样做。

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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM