[英]DB2 SQL select count over union of multiple tables
I need the return the count of records for a certain condition over multiple tables 我需要返回多个表中某个条件的记录数
select count(*) c from table1
where exists (select * from crosstable where crosstable.refid = table1.id)
and crosstable.year = 2014
union
select count(*) c from table2
where exists (select * from crosstable where crosstable.refid = table2.id)
and crosstable.year = 2014
union
select count(*) c from table3
where exists (select * from crosstable where crosstable.refid = table3.id)
and crosstable.year = 2014
this return me a resultset of unique integer values from the table. 这给我返回了表中唯一整数值的结果集。
So if table1 returns '1' and table2 and table3 returns '5' i get '1', '5' instead of '1', '5', '5'. 因此,如果table1返回'1',而table2和table3返回'5',我得到的是'1','5',而不是'1','5','5'。
Also it doens't seem to work to perform 而且它似乎不起作用
select sum(c) from (previous query))
I tried using a sysdummy table but i don't get the syntax quiet right and i cannot find any good examples for this problem. 我尝试使用sysdummy表,但语法不正确,因此找不到任何解决此问题的好例子。 Could be i'm handling it completely wrong.. 可能是我正在完全错误地处理它。
Finally i need my result to be 1 single number and that is the count of each subquery in the union parts 最后,我需要将结果设为1个单一数字,这就是并集部分中每个子查询的计数
Your query 您的查询
select sum(c) from (previous query)
is fine -- almost. 很好-差不多了。 DB2 expects the subquery to have an alias, so try: DB2期望子查询具有别名,因此请尝试:
select sum(c) from (previous query) x
By the way, your union
almost certainly needs to be union all
. 顺便说一下,您的union
几乎肯定需要成为union all
。 union
eliminates duplicates. union
消除重复。
Please try below 请在下面尝试
with temp as (
select count(*) c from table1
where exists (select * from crosstable where crosstable.refid = table1.id)
and crosstable.year = 2014
union all
select count(*) c from table2
where exists (select * from crosstable where crosstable.refid = table2.id)
and crosstable.year = 2014
union all
select count(*) c from table3
where exists (select * from crosstable where crosstable.refid = table3.id)
and crosstable.year = 2014
)
select sum(c) as final_count from temp;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.