如何使用oracle pivot的查询?

kr98yfug  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(336)

我有下面四列。

我能弄到这样的东西吗?

谢谢

tkclm6bt

tkclm6bt1#

我建议使用条件聚合。它是一种独立于数据库的语法,比特定于oracle的语法更灵活 pivot 语法:

select
    piece_id,
    max(case when attrb_code = 'A' then attrb_a_value end) a,
    max(case when attrb_code = 'B' then attrb_a_value end) b,
    max(case when attrb_code = 'C' then attrb_a_value end) c,
    max(case when attrb_code = 'D' then attrb_b_value end) d
from mytable
group by piece_id
hm2xizp9

hm2xizp92#

只是使用 COALESCE (或 NVL )在 PIVOT :

SELECT *
FROM   table_name
PIVOT (
  MAX( COALESCE( attrb_a_value, attrb_b_value ) )
  FOR attrb_code IN (
    'A' AS A,
    'B' AS B,
    'C' AS C,
    'D' AS D
  )
)

因此,对于您的示例数据:

CREATE TABLE table_name ( piece_id, attrb_code, attrb_a_value, attrb_b_value ) AS
SELECT 22333, 'A', 8, NULL FROM DUAL UNION ALL
SELECT 22333, 'B', 9, NULL FROM DUAL UNION ALL
SELECT 22333, 'C', 4, NULL FROM DUAL UNION ALL
SELECT 22333, 'D', NULL, 5 FROM DUAL UNION ALL
SELECT 22332, 'A', 2, NULL FROM DUAL UNION ALL
SELECT 22332, 'B', 3, NULL FROM DUAL UNION ALL
SELECT 22332, 'C', 7, NULL FROM DUAL UNION ALL
SELECT 22332, 'D', NULL, 5 FROM DUAL

这将输出:

PIECE_ID |  A |  B |  C |  D
-------: | -: | -: | -: | -:
   22333 |  8 |  9 |  4 |  5
   22332 |  2 |  3 |  7 |  5

db<>在这里摆弄

相关问题