首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何将多行转置为多列?

如何将多行转置为多列?
EN

Stack Overflow用户
提问于 2018-07-23 05:11:35
回答 1查看 1.9K关注 0票数 0

将seq列升序列值中的col_1分组,以显示以下示例数据的多列注释列中的值:

代码语言:javascript
复制
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 |       |       |       |       |       |       |
-------|-------|-------|-------|-------|-------|-------|-------|
EN

回答 1

Stack Overflow用户

发布于 2018-07-23 05:18:29

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

代码语言:javascript
复制
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;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51469292

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档