【问题标题】:Pivot query Oracle SQL透视查询 Oracle SQL
【发布时间】:2021-06-29 13:18:33
【问题描述】:

我有下表,我正在尝试编写一个 Oracle 选择查询来生成第二个表。

我知道我必须使用 Pivot,但我完全不知道该怎么做。

MSGID KEY COLVALUE
15 height 18
15 length 19
15 width 20
15 notImportant xxx
16 height 21
16 length 22
16 width 23
16 notImportant xxx
17 height 24
17 length 25
17 width 26
17 notImportant xx

想要的结果:

MsgID height length width
15 18 19 20
16 21 22 23
17 24 25 26

尝试了下面的代码,但没有成功....

select MSGID, HEIGHT, LENGTH, WIDTH
     
  from (select MSGID, KEY, COLVALUE              
           from table ) 
  PIVOT
(
    max(COLVALUE)
    FOR KEY IN ('HEIGHT','LENGTH','WIDTH')
) 

你有什么建议吗?

【问题讨论】:

    标签: oracle oracle11g pivot


    【解决方案1】:

    这是一种选择:

    SQL> select msgid,
      2    max(case when key = 'height' then colvalue end) height,
      3    max(case when key = 'length' then colvalue end) length,
      4    max(case when key = 'width'  then colvalue end) width
      5  from test
      6  group by msgid
      7  order by msgid;
    
         MSGID HEIGHT     LENGTH     WIDTH
    ---------- ---------- ---------- ----------
            15 18         19         20
            16 21         22         23
            17 24         25         26
    
    SQL>
    

    或者,pivot:

    SQL> select *
      2  from test
      3  pivot
      4    (max(COLVALUE)
      5     FOR KEY IN ('height','length','width')
      6    )
      7  order by 1;
    
         MSGID 'he 'le 'wi
    ---------- --- --- ---
            15 18  19  20
            16 21  22  23
            17 24  25  26
    
    SQL>
    

    【讨论】:

    • 哇!我是如此接近......枢轴查询就像一个魅力!谢谢!!
    猜你喜欢
    • 2011-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-06
    • 2017-02-22
    相关资源
    最近更新 更多