Click here to Skip to main content
15,885,278 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a data like this

TYPE  RANGE               SALES
A     20180301-20180101     100
A     20171201-20171031   150 
A     20170930-20170731    100
B     20180301-20180101    200
B     20171201- 20171031   200

i want output like this

TYPE 20180301-20180101   20171201-20171031 20170930-20170731
A      100                   150               100


What I have tried:

This is what I have tried

SELECT
FROM
(
SELECT TYPE,MONTH_RANGE,SALES
FROM TABLE
)
pivot
(
    SUM(SALES)
    FOR (MONTH_RANGE) IN (SELECT DISTINCT MONTH_RANGE FROM TABLE)
)


And I tried with XML as well, but its not in a proper format

pivot xml (SUM(SALES) for (month_range) in (SELECT DISTINCT MONTH_RANGE FROM TABLE))


I want this month range to be dynamic not like
for month_range in ('20180301-20180101')
Posted
Updated 26-Apr-18 22:36pm
v3

As far as I know you cannot achieve dynamic pivoting. When a SQL statement is executed, the system needs to know the structure of the result set at compile time. This cannot be achieved if the list of columns would by dynamic

So one possibility is to do this in two phases, first fetch the ranges and then build the SQL statement and execute it. Another approach could be to forget the dynamin pivot and fetch the dynamic portion using a XMLELEMENT
 
Share this answer
 
Comments
Maciej Los 27-Apr-18 4:21am    
5ed!
I'd suggest to read this: Dynamic pivot in oracle sql - Stack Overflow[^] - second solution.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900