繁体   English   中英

取消透视表SQL Oracle

[英]Unpivot Table SQL Oracle

我已经阅读了几篇文章,无法提出解决方案。

我有以下答案表。 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

我需要基于TAG和ORD的以下输出,我需要列出Bank&Amount。

Bank Amount Halifax 32.16 RBS 80.15 Natwest 62.54

到目前为止,我的代码...

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"))

任何帮助将非常感激。 谢谢Genzz

您无需UNPIVOT该数据。 您需要PIVOT 这样可以为您提供所需的结果:

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

您只需要关注最后3行。 test_data SQL只是给出一个有效的示例,而无需访问您的表。

这是另一种方式

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