1

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

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

4

2 回答 2

2

Your query

select sum(c) from (previous query)

is fine -- almost. DB2 expects the subquery to have an alias, so try:

select sum(c) from (previous query) x

By the way, your union almost certainly needs to be union all. union eliminates duplicates.

于 2013-06-27T08:07:26.267 回答
0

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;
于 2015-09-07T13:33:19.237 回答