简体   繁体   English

取消透视表SQL Oracle

[英]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 184的条目数未知,因此,不能对每个金额和名称进行硬编码。

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. 我需要基于TAG和ORD的以下输出,我需要列出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 谢谢Genzz

You don't need to UNPIVOT that data. 您无需UNPIVOT该数据。 You need to PIVOT it. 您需要PIVOT 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. 您只需要关注最后3行。 The test_data SQL is just to give a working example without having access to your tables. test_data SQL只是给出一个有效的示例,而无需访问您的表。

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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM