简体   繁体   中英

Unpivot Table SQL Oracle

I've read a few posts and could not come up with a solution.

I have the following answers table. ID 184 will have an unknown number of entries, so hard-coding each amount and name is not an option.

ID TEXT TAG ORD 184 Halifax Bnk 1 184 RBS Bnk 2 184 Natwest Bnk 3 184 32.16 Amt 1 184 80.15 Amt 2 184 62.54 Amt 3

I need the following output based on TAG and ORD I need to list Bank & Amount.

Bank Amount Halifax 32.16 RBS 80.15 Natwest 62.54

My code so far...

select *  
from 
(select
f.id as "ID"
,a.text as "01TEXT"
,a.tag as  "02TAG"
,a.ord as "03ORD"
from
freq f

left join answers a
on a.freq_id = f.id and a.tag in ('Bnk','Amt')

where
f.id = 184
)unpivot (amount for tag in ("03ORD"))

Any help would be much appreciated. Thanks Genzz

You don't need to UNPIVOT that data. You need to PIVOT it. This gives you the results you are asking for:

with test_data as (
SELECT 184 ID,     'Halifax' text,   'Bnk' tag,     1 ord from dual union all
SELECT 184 ID,     'RBS' text,   'Bnk' tag,     2 ord from dual union all
SELECT 184 ID,     'Natwest' text,   'Bnk' tag,     3 ord from dual union all
SELECT 184 ID,     '32.16' text,   'Amt' tag,     1 ord from dual union all
SELECT 184 ID,     '80.15' text,   'Amt' tag,     2 ord from dual union all
SELECT 184 ID,     '62.54' text,   'Amt' tag,     3 ord from dual
)
select bank_name, amount from test_data
pivot ( max(text) for tag in ('Bnk' as bank_name, 'Amt' as amount) )
order by ord

Only the last 3 lines are of interest to you. The test_data SQL is just to give a working example without having access to your tables.

here is another way

select

f.text  as "Bank"
,a.text as "Amount"
from  answers f
left join answers a
on a.id = f.id 
and a.tag ='Amt'
and a.ord = f.ord

where
f.id = 184
and f.tag = 'Bnk'

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