1

我必须将我的行转换为 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

我希望将其转置(请注意,我不想转置组合)

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

有点苦恼的查询,你能帮忙吗?

4

3 回答 3

3

bhamby当前接受的答案当然是正确的,但是值得检查使用多个相关子查询是否比单个组慢得多(提示:很可能是):

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)

于 2017-07-27T12:51:54.590 回答
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
于 2013-03-20T18:17:22.360 回答
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

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

于 2013-03-20T21:46:16.823 回答