逆透视 Table SQL 甲骨文

Unpivot Table SQL Oracle

我已经阅读了一些帖子,但无法提出解决方案。

我有以下答案table。 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 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"))

如有任何帮助,我们将不胜感激。 谢谢 根兹

您不需要 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'