简体   繁体   中英

Oracle SQL Dynamic Query

I have 2 tables in my Database:

在此处输入图片说明

在此处输入图片说明

I am trying to create a Query that should take in as a variable parameter " id3 " so for example -

Q(z0) should produce

在此处输入图片说明

Thanks in Advance!

Oracle queries can take parameter in 2 forms one is ANSI sql binding [inform of ?] and other is Oracle Style binding [in form of :1].

So your query can be :

    Select * from table1 a, table2 b where a.id1 = b.id1 
and a.id2 = b.id2 and id3 = :1

If I understand you correctly then

SELECT * FROM TAB1 I
         JOIN TAB2 II ON I.id1 = II.id1 and I.id2 = II.id2
WHERE I.id3 = 'z0' 

Should produce the result you require, you may need a "LEFT OUTER JOIN " if TAB2 is incomplete.

So assuming the 'A','B','C' are known the query is

    With extra_cols as(
                    SELECT * FROM (
                                    SELECT * FROM Table2 WHERE id1 = (
                                                                      SELECT id1 FROM TABLE1 WHERE id3 = 'z0'
                                                                      ) 
                                                          AND  id2 = (
                                                                      SELECT id2 FROM TABLE1 WHERE id3 = 'z0'
                                                                      )
                                  )
                  PIVOT (STR(VALUE_1) for FIXED_COL in ('A','B','C')) 
                )
SELECT * from table1 left join extra_cols on table1.id1 = extra_cols.id1 AND table1.id2 = extra_cols.id2
WHERE TABLE1.id3 = 'z0'

The 'A' , 'B' , 'C' String can be extracted from

SELECT FIXED_COL AS Names FROM Table2 WHERE Table2.id1=(SELECT id1 FROM TABLE1 WHERE id3 = 'z0') AND Table2.id2=(SELECT id2 FROM TABLE1 WHERE id3 = 'z0')

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