Oracle SQL - 按列分组并将其他值提取到列

时间:2017-08-10 09:11:26

标签: sql oracle

我的想法是做这样的事情:

INPUT:

ID  CURRENCY    AMOUNT
1   RUS         14,55
1   USD         22,22
1   PLN         444,44
2   PLN         22

然后我想按ID分组并获得输出:

ID  CUR_1   AMOUNT_1    CUR_2   AMOUNT_2    CUR_3   AMOUNT_3
1   RUS     14,55       USD     22,22       PLN     444,44
2   PLN     22

将正确的金额与正确的货币结合起来非常重要。对于ID = 1,最大对数为3。它可能在1到3之间变化。

我尝试使用LISTAGG,但会产生进一步处理数据的问题。

2 个答案:

答案 0 :(得分:3)

select * 
  from (select t.*, row_number() over (partition by id order by null) rn
          from t)
  pivot (max(currency) cur, sum(amount) amt for rn in (1, 2, 3))

测试:

with t(id, currency, amount) as (
    select 1, 'RUS',  14.55 from dual union all
    select 1, 'USD',  22.22 from dual union all
    select 1, 'PLN', 444.44 from dual union all
    select 2, 'PLN',  22    from dual )
select * 
  from (select t.*, row_number() over (partition by id order by null) rn
          from t)
  pivot (max(currency) cur, sum(amount) amt for rn in (1, 2, 3))

输出:

        ID 1_CUR      1_AMT 2_CUR      2_AMT 3_CUR      3_AMT
---------- ----- ---------- ----- ---------- ----- ----------
         1 RUS        14,55 USD        22,22 PLN       444,44
         2 PLN           22   

答案 1 :(得分:0)

您可以使用子查询为每一行创建一个虚拟表,然后按ID将虚拟表连接到一行。