[英]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.