简体   繁体   中英

Using PL/SQL table within SQL query

I have a simple select query like below which has only 2 columns:

SELECT a, b FROM table;

I have some mapping data with me like below:

if a=1 and b=1 then c=100
if a=1 and b=2 then c=200
if a=2 and b=1 then c=300
and so on.

Now, I need to create a query so that I can get output like:

1,1,100
1,2,200
2,1,300
and so on

Here I don't want to create a table and store the mapping data. I can create any data structures in PL/SQL to store it.

How can I achieve this?

PS: I tried to create this mapping data using a PL/SQL table and using INNER JOIN . But I realized PL/SQL tables can not be used in SQL queries.

I am using Oracle 11g.

You can generate the column c output on-the-fly in your query

SELECT a, b,
       case when a=1 and b=1 then 100 
                 a=1 and b=2 then 200 
                 a=2 and b=1 then 300 
       end as c
FROM table;

You can use CASE statement to test the value. The purpose of extra WHERE clause on the following query is to speed up the query a little bit since it will only test for values present on the filter condition.

SELECT  a, b,
        CASE WHEN a = 1 AND b = 1 THEN 100
            WHEN a = 1 AND b = 2 THEN 200
            WHEN a = 2 AND b = 1 THEN 300
        END c
FROM    tableName
WHERE   a IN (1,2) AND
        b IN (1,2)

however, if you want to run in all records, you can just remove the WHERE clause.

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