开发者

Oracle PIVOT, twice?

开发者 https://www.devze.com 2023-01-05 21:21 出处:网络
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 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(splitNam开发者_StackOverflow社区e) 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?


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


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

精彩评论

暂无评论...
验证码 换一张
取 消