数据透视查询 Oracle SQL
Pivot query Oracle SQL
我有下面的 table,我正在尝试编写一个 Oracle select 查询,它会导致第二个 table.
我知道我必须使用 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')
)
你有什么建议吗?
这是一种选择:
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>
我有下面的 table,我正在尝试编写一个 Oracle select 查询,它会导致第二个 table.
我知道我必须使用 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')
)
你有什么建议吗?
这是一种选择:
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>