Oracle查询,需要一行按id输出多行(名称/值对)

时间:2016-10-24 23:52:44

标签: sql oracle name-value

我一直试图解决这个问题。我有一个表,其中有多行包含名称值对,类型和日期(为简单起见未包括)。他们都被身份所束缚。我想在一行中输出与同一个id相关的所有数据,类型为equals document。

  INSERT INTO table1 
    (id, name, val, type)
  VALUES 
    (111, 'direction', 'inbound', 'document'),
    (111, 'filename', 'file.txt', 'document'),
    (111, 'send', 'FOO.SND', 'document'),
    (111, 'rec', 'FOO.RCV', 'document'),
    (111, 'unrelated', 'unrelated', 'business'),
    (222, 'direction', 'inbound2', 'document'),
    (222, 'filename', 'file2.txt', 'document'),
    (222, 'send', 'FOO.SND2', 'document'),
    (222, 'rec', 'FOO.RCV2', 'document'),
    (222, 'unrelated', 'unrelated2', 'business'),
    (333, 'direction', 'inbound3', 'document'),
    (333, 'filename', 'file3.txt', 'document'),
    (333, 'send', 'FOO.SND3', 'document'),
    (333, 'rec', 'FOO.RCV3', 'document'),
    (333, 'unrelated', 'unrelated3', 'business');

我想要输出的是:

    id   direction send      rec       filename
    111  inbound   FOO.SND   FOO.RCV   file.txt
    222  inbound2  FOO.SND2  FOO.RCV2  file2.txt
    333  inbound3  FOO.SND3  FOO.RCV3  file3.txt

1 个答案:

答案 0 :(得分:0)

尝试数据透视查询:

SELECT id,
       MAX(CASE WHEN name = 'direction' THEN val END) AS direction,
       MAX(CASE WHEN name = 'send'      THEN val END) AS send,
       MAX(CASE WHEN name = 'rec'       THEN val END) AS rec,
       MAX(CASE WHEN name = 'filename'  THEN val END) AS filename
FROM table1
GROUP BY id