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
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.
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.