简体   繁体   中英

How to join the table based on main table column value in SQL Server?

I have the following 3 tables:

main_table:

id,name,table_type
1a,sas,1
2a,saw,1
3a,sdd,2

inst_table

id,inst_name,rating
1a,sdsdf,3
2a,erer,4

indv_table

id,ind_name,rating
3a,gbgbg,3
5a,gff,4

How to join the subtables based on main_table column:'table_type' ?

Ie, if main table column: table_type = 1 , then it has to join with table:'inst_table' else table:'indv_table'

SELECT *
  FROM main_table t1
    INNER JOIN inst_table t2 ON T1.ID = T2.ID where t1.table_type=1
UNION ALL
  SELECT *
  FROM main_table T1
    INNER JOIN indv_table T3 ON T1.ID = T3.ID where t1.table_type=2

You can left join both sub-tables to main_table:

proc sql;
select m.*, i.*, d.* 
from main_table as m 
left join inst_table as i on m.id=i.id and m.table_type = 1
left join indv_table as d on m.id=d.id and m.table_type ne 1
;
quit;

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