Oracle PIVOT, twice?

倖福魔咒の 提交于 2020-01-01 18:59:44

问题


I have been trying to move away from using DECODE to pivot rows in Oracle 11g, where there is a handy PIVOT function. But I may have found a limitation:

I'm trying to return 2 columns for each value in the base table. Something like:

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)
            )

I can do this with DECODE, but I can't wrestle the syntax to let me do it with PIVOT. Is this even possible? Seems like it wouldn't be too hard for the function to handle.

Edit: is StackOverflow maybe not the right Overflow for SQL questions?

Edit: anyone out there?


回答1:


From oracle-developer.net it would appear that it can be done like this:

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)
            )



回答2:


I'm not sure from what you provided what the data looks or what exactly you would like. Perhaps if you posted the decode version of the query that returns the data you are looking for and/or the definition for the source data, we could better answer your question. Something like this would be helpful:

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)
);


来源:https://stackoverflow.com/questions/3197802/oracle-pivot-twice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!