Oracle PIVOT,两次?

时间:2010-07-07 18:40:55

标签: sql oracle pivot oracle11g

我一直在努力摆脱使用DECODE来转移Oracle 11g中的行,这里有一个方便的PIVOT功能。但我可能已经找到了一个限制:

我正在尝试为基表中的每个值返回2列。类似的东西:

SELECT somethingId, splitId1, splitName1, splitId2, splitName2
FROM (SELECT somethingId, splitId
      FROM SOMETHING JOIN SPLIT ON ... )
      PIVOT ( MAX(splitId) FOR displayOrder IN (1 AS splitId1, 2 AS splitId2),
              MAX(splitName) FOR displayOrder IN (1 AS splitName1, 2 as splitName2)
            )

我可以用DECODE做到这一点,但是我无法通过语法来解决让我用PIVOT做的事情。这甚至可能吗?似乎功能处理起来并不难。

编辑:StackOverflow可能不是SQL问题的正确溢出吗?

编辑:那里有人吗?

2 个答案:

答案 0 :(得分:2)

oracle-developer.net来看,似乎可以这样做:

SELECT somethingId, splitId1, splitName1, splitId2, splitName2
FROM (SELECT somethingId, splitId
      FROM SOMETHING JOIN SPLIT ON ... )
      PIVOT ( MAX(splitId)  ,
              MAX(splitName) 
              FOR displayOrder IN (1 AS splitName1, 2 as splitName2)
            )

答案 1 :(得分:1)

我不确定您提供的数据是什么或者您想要什么。也许如果您发布了返回您要查找的数据的查询的解码版本和/或源数据的定义,我们可以更好地回答您的问题。这样的事情会有所帮助:

create table something (somethingId Number(3), displayOrder Number(3)
   , splitID Number(3));            
insert into something values (1, 1, 10);
insert into something values (2, 1, 11);
insert into something values (3, 1, 12);
insert into something values (4, 1, 13);
insert into something values (5, 2, 14);
insert into something values (6, 2, 15);
insert into something values (7, 2, 16);

create table split (SplitID Number(3), SplitName Varchar2(30));
insert into split values (10, 'Bob');
insert into split values (11, 'Carrie');
insert into split values (12, 'Alice');
insert into split values (13, 'Timothy');
insert into split values (14, 'Sue');
insert into split values (15, 'Peter');
insert into split values (16, 'Adam');

SELECT * 
FROM (
   SELECT somethingID, displayOrder, so.SplitID, sp.splitname
      FROM SOMETHING so JOIN SPLIT sp ON so.splitID = sp.SplitID
)
PIVOT ( MAX(splitId) id,  MAX(splitName) name
   FOR (displayOrder, displayOrder) IN ((1, 1) AS split, (2, 2) as splitname)
);