简体   繁体   中英

how to select a column based on the value of a row from another table in oracle

I have 2 tables as follows. I would like to select a column from the second table based on the value of the row from the first table

table1                       table2
id     pos1   pos2         id1      id2      id3      position
41a1   A1T1   V1          1122     41a1      99a1     A1T1V1
1133   A1T1   V2          1133     41a2      99a2     A1T1V2
99a3   A1T1   V3          1144     41a3      99a3     A1T1V3
41a2   A1T1   V4
41a3   A1T1   V5

How to do a select query in oracle

select t1.id,(t2.id1 or t2.id2 or t2.id3) from t1,t2 where t1.pos1||t1.pos2= t2.position; 

t2.id1 t2.id2 or t2.id3 is based on the value if t1.id similar to the if loop below:

if t1.pos1 ='A1T1' and substr(t2.position,1,4)='A1T1' and substr(t1.id,1,2)='41' 
  then 
      t2.id2 
  elseif 
     substr(t1,id,1,2)='99' 
  then  
      t2.id3 
  else 
     t2.id1

It sounds like you want a case statement

select t1.id,
       (case when t1.pos1 ='A1T1' 
              and substr(t2.position,1,4)='A1T1' 
              and substr(t1.id,1,2)='41' 
             then t2.id2
             when substr(t1,id,1,2)='99' 
             then t2.id3 
             else t2.id1 
         end)
   ...

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