繁体   English   中英

DB2 SQL选择计数多个表的并集

[英]DB2 SQL select count over union of 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

这给我返回了表中唯一整数值​​的结果集。

因此,如果table1返回'1',而table2和table3返回'5',我得到的是'1','5',而不是'1','5','5'。

而且它似乎不起作用

select sum(c) from (previous query))

我尝试使用sysdummy表,但语法不正确,因此找不到任何解决此问题的好例子。 可能是我正在完全错误地处理它。

最后,我需要将结果设为1个单一数字,这就是并集部分中每个子查询的计数

您的查询

select sum(c) from (previous query)

很好-差不多了。 DB2期望子查询具有别名,因此请尝试:

select sum(c) from (previous query) x

顺便说一下,您的union几乎肯定需要成为union all union消除重复。

请在下面尝试

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.

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