2013-05-30 71 views
1

我有以下表選擇UNION ALL光標

tab_1: 

(rs) 
rs1 
rs2 
rs3 

tab_2: 

(rs) (cell) (tf) 
rs1 A549 tf1 
rs1 C555 tf2 
rs3 B333 tf1 

我需要循環的tab_1中僅列,並檢查:

SELECT count(distinct cell) from tab_2 where rs = 'rs1' 
union all 
SELECT count(distinct cell) from tab_2 where rs = 'rs2' 
union all 
SELECT count(distinct cell) from tab_2 where rs = 'rs3'; 

並得到結果

2 
0 
1 

燦不明白光標應該如何工作或只是一個簡單的循環(

回答

2

如果要包括零計數rs2,這是tab_1但不是tab_2,你需要一個LEFT JOIN

而且,你不需要UNION每個值 - 基本GROUP BY將這樣的伎倆:

SELECT tab_1.rs, COUNT(DISTINCT tab_2.cell) 
FROM tab_1 
LEFT JOIN tab_2 ON tab_1.rs = tab_2.rs 
GROUP BY tab_1.rs 
ORDER BY tab_1.rs 

使用您的樣本數據,這個查詢的結果是:

rs1 2 
rs2 0 
rs3 1 

有一個SQLFiddle here

+0

非常感謝!完美的作品。 –