DB2 SQL select count over多个表的联合

时间:2013-06-27 07:37:07

标签: sql db2

我需要在多个表中返回特定条件的记录计数

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个单一数字,这是联合部分中每个子查询的计数

2 个答案:

答案 0 :(得分:2)

您的查询

select sum(c) from (previous query)

很好 - 几乎。 DB2期望子查询具有别名,因此请尝试:

select sum(c) from (previous query) x

顺便说一句,您的union几乎肯定需要union allunion可以消除重复。

答案 1 :(得分:0)

请尝试以下

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;