【问题标题】:Is there a way for me to pivot these rows into columns in oracle?有没有办法让我将这些行转换为 oracle 中的列?
【发布时间】:2020-03-07 12:28:17
【问题描述】:

我有一个看起来像附件图片的数据库表

enter image description here 我需要对此进行查询并能够以以下格式显示输出 BookID, Genre1, Genre2, Genre3

我已经阅读了一些关于旋转/使用 MAX 功能的以前的帖子,但我仍在苦苦挣扎,我是新手。

【问题讨论】:

    标签: sql database oracle pivot


    【解决方案1】:

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

    select bookId,
           max(case when seqnum = 1 then genre end) as genre_1,
           max(case when seqnum = 2 then genre end) as genre_2,
           max(case when seqnum = 3 then genre end) as genre_3
    from (select bg.*, 
                 row_number() over (partition by bookId order by genre) as seqnum
          from bookGenres
         ) bg
    group by bookId;
    

    【讨论】:

    • 非常感谢,这真的很有帮助。如果我有一个名为 Books 的表,其中包含书籍 ID 和名称,第二个表名为 Genre,具有流派代码和流派名称,然后 bookgenre 作为我的第三个表,只有书籍 ID 和流派 ID。 (对不起,如果这是一个愚蠢的问题)即我需要从书到书流到流派
    • @va9999 。 . .那么你会有一个不同的问题。这应该作为一个新问题提出。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-23
    • 2019-10-03
    • 1970-01-01
    • 2014-04-19
    • 1970-01-01
    • 2020-10-13
    • 2014-11-06
    相关资源
    最近更新 更多