【问题标题】:How to transpose multiple rows into multiple columns?如何将多行转换为多列?
【发布时间】:2018-07-22 21:11:35
【问题描述】:

在 seq 列的升序值中对 col_1 进行分组,以在以下示例数据的多列中显示来自注释列的值:

col_1  |  Seq  |  Comment |
--------------------------|
ABC    |   30  |  TestC   |
ABC    |   50  |  TestE   |
ABC    |   80  |  TestG   |
ABC    |   10  |  TestA   |
ABC    |   60  |  TestF   |
ABC    |   20  |  TestB   |
ABC    |   70  |  TestF   |
ABC    |   40  |  TestD   |
DEF    |   20  |  TestB   |
DEF    |   10  |  TestA   |
GHI    |   10  |  TestA   |
--------------------------|

Expected output of sql should be:
Col_1  | Col_2 | Col_3 | Col_4 | Col_5 | Col_6 | Col_7 | Col_8 | 
-------|-------|-------|-------|-------|-------|-------|-------|
ABC    | TestA | TestB | TestC | TestD | TestE | TestF | TestG |
DEF    | TestA | TestB |       |       |       |       |       |
GHI    | TestA |       |       |       |       |       |       |
-------|-------|-------|-------|-------|-------|-------|-------|

【问题讨论】:

    标签: sql oracle oracle11g pivot


    【解决方案1】:

    可以使用条件聚合和row_number()

    select col_1,
           max(case when seqnum = 1 then comment end) as col_2,
           max(case when seqnum = 2 then comment end) as col_3,
           max(case when seqnum = 3 then comment end) as col_4,
           . . .
    from (select t.*,
                 row_number() over (partition by col_1 order by seq) as seqnum
          from t
         ) t
    group by col_1;
    

    【讨论】:

    • 使用 CASE 或 DECODE 会不必要地使用大量代码。我想避免硬编码类型的编码并使用 SQL 的高级功能。即使是程序也会有所帮助。
    • @RinkuGautam 。 . .这回答了您提出的问题。如果您还有其他问题,则应将其作为问题提出。
    【解决方案2】:

    这基本上使用了与 Gordon 的答案相同的 row_number 函数,但使用了 PIVOT 子句。

    SELECT *
    FROM (
        SELECT t.COL_1
            ,t.comments
            ,row_number() OVER (
                PARTITION BY col_1 ORDER BY seq
                ) AS seqnum
        FROM t
        ) t
    PIVOT(MAX(comments) FOR seqnum IN (1 as col_2,2 as col_3,3 as col_4,
                                       4 as col_5,5 as col_6,6 as col_7,
                                       8 as col_8));
    

    Demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-27
      • 1970-01-01
      • 2022-11-17
      • 2014-01-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多