在SQL列中添加查询结果

时间:2016-09-29 13:09:15

标签: sql oracle pivot crosstab

我有这个(我的查询结果):

    id |  suk | xpto
   ----+------+------
     4 | 1023 | abc
     4 | 1025 | def
     4 | 1200 | zzz
     4 | 1501 | ppp
     5 | 1111 | ola
     5 | 2222 | xau

我需要转换

    id |   suk    |    suk2  |   suk3   | suk4 
  -----+----------+----------+----------+-----------
     4 | 1023 abc | 1025 def | 1200 zzz | 1501 ppp
     5 | 1111 ola | 2222 xau |          |

实际上,我的查询是:

SELECT b.ID, s.SKU, s.EVENT_TYPE 
FROM VFIE_BONUS_POINTS_RULE b 
INNER JOIN VFIE_BONUS_POINTS_RULE_SKU s  
ON b.ID = s.ID_BNS_PTS_RL; 

我使用Oracle。

有可能吗?

2 个答案:

答案 0 :(得分:0)

使用pivotrow_number()。而不是t放置您的查询:

select * 
  from (select row_number() over (partition by id order by suk) rn, t.* from t)
  pivot (max(suk||' '||xpto) suk for rn in (1, 2, 3, 4))

测试:

with t(id, suk, xpto) as (select 4, 1023, 'abc' from dual
                union all select 4, 1025, 'def' from dual
                union all select 4, 1200, 'zzz' from dual
                union all select 4, 1501, 'ppp' from dual
                union all select 5, 1111, 'ola' from dual
                union all select 5, 2222, 'xau' from dual )
select * 
  from (select row_number() over (partition by id order by suk) rn, t.* from t)
  pivot (max(suk||' '||xpto) suk for rn in (1, 2, 3, 4))

输出:

ID  1_SUK     2_SUK     3_SUK     4_SUK
--  --------  --------  --------  --------
 4  1023 abc  1025 def  1200 zzz  1501 ppp
 5  1111 ola  2222 xau

修改:

  

如何更改sku和xpto的列名?预计:SUK 1 -   XPTO 1

select id,"1_S" as "SUK 1", "1_X" as "XPTO 1", 
          "2_S" as "SUK 2", "2_X" as "XPTO 2", 
          "3_S" as "SUK 3", "3_X" as "XPTO 3", 
          "4_S" as "SUK 4", "4_X" as "XPTO 4"
  from (select row_number() over (partition by id order by suk) rn, t.* from t)
  pivot (max(suk) s, max(xpto) x for rn in (1, 2, 3, 4) )

有关Oracle documentationpivot的更多信息。

答案 1 :(得分:0)

如何更改新列名?现在,我有1_Suk,2_Suk,3_Suk,我需要这个:Suk 1,Suk 2,Suk 3.