Oracle Pivot行成列

时间:2019-05-17 03:21:11

标签: sql database oracle plsql pivot

我有一个如下表:

PART_ID  | ATTR_GROUP | ATTR_VALUE1 | ATTR_VALUE2 | COLUMN_NAME
--------------------------------------------------
M2CV4    | GROUP-A    | MATERIAL   |   N/A        |  ATTR_X1
M2CV4    | GROUP-A    | GRADE      |    A         |  ATTR_X2
M2CV4    | GROUP-B    | DOC ID     |   1234       |  ATTR_X1
M2CV4    | GROUP-B    | DOC TYPE   |   XX         |  ATTR_X2

我想使表格看起来像这样:

PART_ID | ATTR_GROUP | ATTR_X1 | ATTR_X1_VALUE | ATTR_X2    | ATTR_X2_VALUE
---------------------------------------------------------------------------
M2CV4   | GROUP-A    | MATERIAL|   N/A         | GRADE      |  A
M2CV4   | GROUP-B    | DOC ID  |   1234        | DOC TYPE   | XX

一个部件ID可以有多个文档,因此,如果M2CV4有3个文档,则输出为

PART_ID | ATTR_GROUP | ATTR_X1 | ATTR_X1_VALUE | ATTR_X2| ATTR_X2_VALUE
---------------------------------------------------------------------------
M2CV4   | GROUP-A    | MATERIAL|   N/A         | GRADE      |  A
M2CV4   | GROUP-B    | DOC ID  |   1234        | DOC TYPE   | XX
M2CV4   | GROUP-B    | DOC ID  |   456         | DOC TYPE   | XX
M2CV4   | GROUP-B    | DOC ID  |   333         | DOC TYPE   | XX

Oracle数据库12c-12.2.2版本。 我在这里给出2个列的示例,但是根据组和column_name

,我确实有很多列

感谢您的帮助。赞赏。

1 个答案:

答案 0 :(得分:0)

如果我理解正确,则希望在不同的行上重复。我建议无论如何都要使用条件聚合。如果这样做,可以使用row_number()解决问题:

select part_id, attr_group,
       max(case when column_name = 'ATTR_X1' then attr_value end) as attr_x1,
       max(case when column_name = 'ATTR_X2' then attr_value end) as attr_x2
from (select t.*,
             row_number() over (partition by part_id, attr_group, column_name order by column_name) as seqnum
      from t
     ) t
group by part_id, attr_group, seqnum;