2013-06-27 108 views
0

的工会,我需要返回的记录数一定条件下多个表DB2 SQL SELECT COUNT多个表

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支单数,这是每个子查询的联合零件计数

+0

什么结果集,你希望要回?所有三项计数的总和? – rabs

+0

是的,更新我的问题:) – JMan

回答

2

您的查询

select sum(c) from (previous query) 

很好 - 差不多。 DB2预计子查询中有一个别名,所以尝试:

select sum(c) from (previous query) x 

顺便说一句,你union几乎肯定需要是union allunion消除重复。

+0

作品,谢谢 – JMan

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; 
+0

你应该添加一个关于你修复什么的简短说明。 – spenibus