sql - Link tables based on column value -


is possible pull values 2 different tables based on value of column? example, have table boolean column either returns 0 or 1 depending on end user selects in our program. 0 means should pull in default values. 1 means use user's data.

if table table1 looked this:

case id      boolean ====================     1              0     2              1     3              1     4              0     5              0 

then need pull case ids 1,4,and 5's corresponding data table default , case ids 3 , 4's corresponding data table userdef. have take these values, combine them, , reorder them case id can preserve order in resulting table.

i inexperienced sql trying learn. or suggestions appreciated. thank in advance help.

something this:

select    t1.caseid  ,case when t1.boolean = 1 dt.col1 else ut.col1 end col1  ,case when t1.boolean = 1 dt.col2 else ut.col2 end col2  table1 t1 left join defaulttable dt on dt.caseid = t1.caseid left join userdeftable ut on ut.caseid = t1.caseid order t1.caseid 

you join on both tables , use case in select choose 1 display data.

option b:

with cte_combo (    select 0 boolean, * default     --replace * needed columns    union     select 1 boolean, * userdef     --replace * needed columns ) select * table1 t left join cte_combo c on t.caseid = c.caseid , t.boolean = c.boolean order t.caseid 

this might simpler - using cte make union of both tables adding artificial column, , join cte , table using both id , flag column.


Comments