2013-06-27 137 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