简体   繁体   中英

Select union all cursor

I have the following tables

tab_1: 

(rs)
rs1
rs2
rs3

tab_2: 

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

I need to loop on the tab_1 only column and check:

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

and get the result

2
0
1

Can't understand how Cursor should work or just a simple loop(

If you want to include the zero count for rs2 , which is in tab_1 but not tab_2 , you need a LEFT JOIN

Also, you don't need to UNION for each value - a basic GROUP BY will do the trick:

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

Using your sample data, the result of this query is:

rs1   2
rs2   0
rs3   1

There's a SQLFiddle here .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM