在DB2中进行透视

时间:2013-03-20 16:20:26

标签: sql db2 pivot

我必须将我的行转换为DB2表中的列。这就是我的表的结构。

ItemID    Item    Value
---------------------
1     Meeting     Now
1     Advise      Yes
1     NoAdvise    No
2     Meeting     Never
2     Advise      No
2     NoAdvise    Null
2     Combine    Yes

我希望将其转换为(注意我不想转置Combine)

ItemID    Meeting  Advise   NoAdvise 
---------------------------------------
1         Now      Yes       No
2         Never    No        Null

有点挣扎于查询,你能帮忙吗?

3 个答案:

答案 0 :(得分:2)

它不是很漂亮,但应该有效。 DB2没有内置的PIVOT函数,如SQL Server。

SELECT DISTINCT
     A.ItemID
    ,(SELECT value
      FROM table B
      WHERE B.ItemID = A.ItemID
        AND B.Item   = 'Meeting'
    ) AS Meeting
    ,(SELECT value
      FROM table B
      WHERE B.ItemID = A.ItemID
        AND B.Item   = 'Advise'
    ) AS Advise
    ,(SELECT value
      FROM table B
      WHERE B.ItemID = A.ItemID
        AND B.Item   = 'NoAdvise'
    ) AS NoAdvise
FROM table A

答案 1 :(得分:1)

currently accepted answer by bhamby肯定是正确的,但值得检查if using several correlated subqueries is much slower than a single group by(提示:最有可能):

SELECT 
  A.ItemID,
  MAX(CASE WHEN A.Item = 'Meeting'  THEN Value END) AS Meeting,
  MAX(CASE WHEN A.Item = 'Advise'   THEN Value END) AS Advise,
  MAX(CASE WHEN A.Item = 'NoAdvise' THEN Value END) AS NoAdvise
FROM A
GROUP BY A.ItemID

我认为这也有点简单

SQLFiddle(在PostgreSQL中,但也适用于DB2 LUW)

答案 2 :(得分:0)

正如@bhamby所说,DB2没有PIVOT功能 大多数情况下,我的查询只是在检索结果的方式上有所不同 - 您需要在它们上运行探查器/优化器以确保,但我相信相关的子查询可能会按行执行(可能效率较低),而不是作为集合。这不太可能是小数据集的问题。

WITH Item (id) as (SELECT DISTINCT itemId
                   FROM YourTable),
SELECT item.id, Meeting.meeting, Advise.advise, NoAdvise.noadvise
FROM Item
LEFT JOIN (SELECT itemId, value as meeting
           FROM YourTable
           WHERE item = 'Meeting') as Meeting
       ON Meeting.itemId = Item.id
LEFT JOIN (SELECT itemId, value as advise
           FROM YourTable
           WHERE item = 'Advise') as Advise
       ON Advise.itemId = Item.id
LEFT JOIN (SELECT itemId, value as noadvise
           FROM YourTable
           WHERE item = 'NoAdvise') as NoAdvise
       ON NoAdvise.itemId = Item.id

(...实际上,我有点担心你有'建议'和'没有建议'的列,这似乎是某种布尔条件 - 即,你应该有一个,但不是另一个)。