oracle 10g将特定键的多个记录合并到不同的列

时间:2017-02-13 20:23:47

标签: sql oracle

我是sql编程的新手,想知道是否可以执行以下操作 我有表x及以下数据

表x

CODE      CUSTOMER        CLASS
 1            11            F
 1            12            P
 1            13            F
 1            14            F

我想将CODE = 1的所有记录显示在一条记录中,就像这样

CODE      CUSTOMER_A   CUSTOMER_B   CUSTOMER_C ...
 1            11           12           13

我需要在sigle行的不同列上显示相同CODE和CLASS = F的所有客户,CUSTOMER的值需要显示在CUSTOMER_A列中,CUSTOMER_B列上的下一个值,依此类推。

2 个答案:

答案 0 :(得分:1)

希望,我理解你的问题,

正如您在评论中提到的,将有最多4或5位客户。我认为以下查询可能有所帮助。请检查

select CODE , 
max(case when rn = 1 then customer end) customer_a ,
max(case when rn = 2 then customer end) customer_b ,
max(case when rn = 3 then customer end) customer_c ,
max(case when rn = 4 then customer end) customer_d ,
max(case when rn = 5 then customer end) customer_e 
from
(
SELECT CODE , CUSTOMER , row_number() over (partition by code order by rowid ) rn
  FROM TABLE_X 
  where code = 1
  and class='F'

)  
group by code
  ;

答案 1 :(得分:0)

另一个有用的选择是下一个代码,不知道它是否正确但是也可以。

  SELECT CODE, 
     MAX(CASE WHEN ROWNUM = 1 THEN customer  END) customer_a ,
     MAX(CASE WHEN ROWNUM = 2 THEN customer  END) customer_c ,
     MAX(CASE WHEN ROWNUM = 3 THEN customer  END) customer_d ,
     MAX(CASE WHEN ROWNUM = 3 THEN customer  END) customer_e
  from TABLE_X
  where code = 1
 and class='F'
GROUP BY code