Pivoting; dynamic pivot_in_clause
I have this situation:
create table pivot_data
(group_id NUMBER(10),
address_state VARCHAR2(20),
address_zip VARCHAR2(5),
skill_id NUMBER(10),
person_id NUMBER(10),
person_name VARCHAR2(20)
INSERT INTO pivot_data VALUES (1,'VIRGINIA','22222',10,100,'JOHN');
INSERT INTO pivot_data VALUES (1,'VIRGINIA','22222',10,200,'JEFF');
INSERT INTO pivot_data VALUES (1,'VIRGINIA','22222',10,300,'GEORGE');
INSERT INTO pivot_data VALUES (2,'VIRGINIA','22222',10,400,'KATE');
INSERT INTO pivot_data VALUES (2,'VIRGINIA','22222',10,500,'KELLY');
INSERT INTO pivot_data VALUES (3,'VIRGINIA','22222',10,600,'SAM');
INSERT INTO pivot_data VALUES (4,'VIRGINIA','22222',20,100,'JOHN');
INSERT INTO pivot_data VALUES (4,'VIRGINIA','22222',20,200,'JEFF');
INSERT INTO pivot_data VALUES (4,'VIRGINIA','22222',20,300,'GEORGE');
INSERT INTO pivot_data VALUES (5,'VIRGINIA','22222',20,400,'KATE');
INSERT INTO pivot_data VALUES (5,'VIRGINIA','22222',20,500,'KELLY');
INSERT INTO pivot_data VALUES (5,'VIRGINIA','22222',20,600,'SAM');
COMMIT;
SELECT * FROM pivot_data;
1 VIRGINIA 22222 10 100 JOHN
1 VIRGINIA 22222 10 200 JEFF
1 VIRGINIA 22222 10 300 GEORGE
2 VIRGINIA 22222 10 400 KATE
2 VIRGINIA 22222 10 500 KELLY
3 VIRGINIA 22222 10 600 SAM
4 VIRGINIA 22222 20 100 JOHN
4 VIRGINIA 22222 20 200 JEFF
4 VIRGINIA 22222 20 300 GEORGE
5 VIRGINIA 22222 20 400 KATE
5 VIRGINIA 22222 20 500 KELLY
5 VIRGINIA 22222 20 600 SAM
Business rules:
1.People from a given state, zip code are grouped based on their skillset.
2.A person may have more than one skillset
3.A person can be part of different groups . Even a person can belong to more than one group for same skill id in case
groups are made again for same skill set
4.A group can have at the most 3 members
5.I am using Oracle 11g. Don't know how to use 11g pivot function because pivot_in_clause in my case is dynamic
I want to pivot the data in order to show each group in one row:
state zip skill_id member1 member1_name member2 member2_name member3 member3_name
VIRGINIA 22222 10 100 JOHN 200 JEFF 300 GEORGE
VIRGINIA 22222 10 400 KATE 500 KELLY
VIRGINIA 22222 10 600 SAM
VIRGINIA 22222 20 100 JOHN 200 JEFF 300 GEORGE
VIRGINIA 22222 20 400 KATE 500 KELLY 600 SAM
Thanks for the help!
RN
Hi,
Thanks for posting the CREATE TABLE and INSERT statements; that's very helpful!
RN wrote:
... Business rules:
1.People from a given state, zip code are grouped based on their skillset.
2.A person may have more than one skillset
3.A person can be part of different groups . Even a person can belong to more than one group for same skill id in case
groups are made again for same skill set
4.A group can have at the most 3 members
5.I am using Oracle 11g. Don't know how to use 11g pivot function because pivot_in_clause in my case is dynamic
It's dynamic only in that the value that tells which person appears in which column has to be derived at run time.
It's not dynamic in the sense that the number of columns is fixed: you always want 9 columns (3 for group information, and then 3 pivoted sets of 2 columns each).
I want to pivot the data in order to show each group in one row:
state zip skill_id member1 member1_name member2 member2_name member3 member3_name
VIRGINIA 22222 10 100 JOHN 200 JEFF 300 GEORGE
VIRGINIA 22222 10 400 KATE 500 KELLY
VIRGINIA 22222 10 600 SAM
VIRGINIA 22222 20 100 JOHN 200 JEFF 300 GEORGE
VIRGINIA 22222 20 400 KATE 500 KELLY 600 SAM Sorry, I'm not at an Oracle 11 database right now, so I can't test a solution using SELECT ... PIVOT. I'm not sure it would really help, anyway.
Here's how you can do it in Oracle 9 (and up):
WITH got_c_num AS
SELECT group_id, address_state
, address_zip, skill_id
, person_id, person_name
, ROW_NUMBER () OVER ( PARTITION BY group_id, address_state
, address_zip, skill_id
ORDER BY person_id
) AS c_num
FROM pivot_data
SELECT address_state
, address_zip, skill_id
, MIN (CASE WHEN c_num = 1 THEN person_id END) AS member1
, MIN (CASE WHEN c_num = 1 THEN person_name END) AS member1_name
, MIN (CASE WHEN c_num = 2 THEN person_id END) AS member2
, MIN (CASE WHEN c_num = 2 THEN person_name END) AS member2_name
, MIN (CASE WHEN c_num = 3 THEN person_id END) AS member3
, MIN (CASE WHEN c_num = 3 THEN person_name END) AS member3_name
FROM got_c_num
GROUP BY group_id, address_state
, address_zip, skill_id
ORDER BY group_id, address_state
, address_zip, skill_id
;
Similar Messages
-
Pivot Dynamic for Query in Oracle SQL DEVELOPER ??
Hi
I have the following question, someone who has a dynamic pivot.
I need a dynamic query that is that when the transfer column to row do receiving any type declared as these can change data.
Example:
ID_PROJECT
PROJECT STAGES
DATE
12345
Requirement Analysis
17-01-2013
12345
Quotation
20-01-2013
12345
Project Preparation
29-01-2013
12345
Model Verification
04-02-2013
12345
Closed requirement
10-02-2013
23456
Building and Unit Tests
With dynamic pivot:
ID_PROJECT
Requirement Analysis
Quotation
Project Preparation
Model Verification
Closed requirement
12345
17-01-2013
20-01-2013
29-01-2013
04-02-2013
10-02-2013
I mean that in this case the stages of the project will be changing.Hello,
Do you want to do this in an SQL - Developer application-setting or by using any SQL / PLSQL block or both ? -
Hi all
We have been designing resource management system and want to provide flexible way to extend resource properties at runtime. So we are storing resource properties in a single table, e.g.
select * from _kv
ID K V
1 name Bob
1 age 30
1 gender male
2 name Susan
2 status married
convert to
+-----+-------+--------+----------+
| key | color | height | whatever |
+-----+-------+--------+----------+
| 1 | green | 15 | --- |
| 2 | --- | --- | lol |
+-----+-------+--------+----------+
example of dynamic pivot Dynamic SQL Pivoting &#8211; Stealing Anton&#8217;s Thunder</title> //<title>AMIS Technology Blog…
Is it possible to create interactive report with dynamic columns updated when _kv will be changed?
Is it possible to create add/edit dynamic form depends on key set if we add value type description?
Thanksmake sure you put some thought into your database design before you go too far.
There are many horror stories about EAV based schema designs. (which this design seems to be heading.)
Read up on them before you go too far.
-- back to being on topic --
AFAIK you can not do dynamic SELECT with an Interactive Report.
However, you can with a Basic Report. But, it is non-trivial. (ie it is difficult to do)
Basic Report can use a "function returning SELECT statement".
You will also need to name the columns based on a different function.
In order to 'synchronize' the column names with the SELECT statement, you will need a 3rd function that properly generates them.
This 3rd function MUST have an 'ORDER BY' clause.
Both the generateSELECT() function and the generateCOLUMN_NAMES() function will call that 3rd function.
From a code management standpoint, you will need to create a package that contains all three functions.
are you sure you want to go this route?
are you ready to go this route?
Again, think about your table designs.
MK -
How to display more than 60 columns in a report
I have a table defined as follows
id
column_name
column_value
data sample
id col_name column_value
1 col1 val1
1 col2 val2
1 col3 val3
2 col1 val1
2 col2 val2
2 col3 val3
now I want to display the data in a report as follows
id col1 col2 col3
1 val1 val2 val3
2 val1 val2 val3
I was able to generate output using pivots [http://technology.amis.nl/blog/1197/pivot-dynamic-data]
the problem is that I can have more that 60 columns retrieved in each row, the pivot solution will retrieve them correctly but I can't display more than 60 columns in apex reports, why this restriction in apex, any solutionHello:
In the Source section of the report definition choose 'Use Generic Column Names (parse query at runtime only)' and then specify a suitable value for 'Maximum number of generic report columns:'
Varad -
Dear All,
I want following column wise Production Report (From Production Order)
WARE HOUSE UOM COMPLETED Date(1,2,3,4,5,6,......31 ) Completed Qty. total qty
Basically i want Pivot (dynamic) by date
SELECT T0.[Warehouse], T0.[Uom], T0.[DueDate], T0.[CmpltQty] FROM OWOR T0 WHERE T0.[Status] ='L' GROUP BY T0.[Warehouse], T0.[Uom], T0.[DueDate], T0.[CmpltQty]
thanks
Ashish GupteHi,
Hope this will help you
DECLARE @listCol VARCHAR(2000)
DECLARE @query VARCHAR(4000)
SELECT @listCol = STUFF(( SELECT DISTINCT
'],[' + CONVERT(VARCHAR,DueDate,102)
FROM OWOR
FOR XML PATH('')
), 1, 2, '') + ']'
SET @query =
'SELECT * FROM
(SELECT Warehouse, Uom, (DueDate) Date , CmpltQty
FROM OWOR WHERE Status =''L''
GROUP BY Warehouse, Uom, DueDate, CmpltQty
) S
PIVOT (Sum(CmpltQty) FOR Date
IN ('@listCol')) AS pvt'
EXECUTE (@query)
Regards
Edited by: Pari Minhas on Aug 18, 2011 3:42 AM -
SQL Server 2012 Three Tables Joining
I have Three Tables in sqlserver2012
Master Table
OrderID PackageID CustomerName
1 1 Abc
2 2 Bcd
3 1 xyz
Child1 Table
OrderID ControlName
1 Row1COlumn1 (It Means Pant in Red Color is selected by user(relation with Child2 Table))
1 Row3Column1 (It Means Gown in Blue Color is selected by user(relation with Child2 Table))
1 Row4Column3 (It Means T Shirt in White Color is selected by user(relation with Child2 Table))
2 Row1Column2 (It Means Tie in Green Color is selected by user(relation with Child2 Table))
2 Row3Column1 (It Means Bow in Red Color is selected by user(relation with Child2 Table))
Child2 Table
PackageID Product Color1 Color2 Color3
1 Pant Red Green Blue
(Row1 of Package 1)
1 Shirt Blue Pink Purple
(Row2 of Package 1)
1 Gown Blue Black Yellow
(Row3 of Package 1)
1 T Shirt Red Green White
(Row4 of Package 1)
2 Tie Red Green
White
(Row1 of Package 2)
2 Socks Red Green White
(Row2 of Package 2)
2 Bow Red Green White
(Row3 of Package 2)
I want to have result like
OrderID PackageID CustomerName Pant Gown T Shirt Tie Bow
1 1 ABC
Red Blue White x x
2 2 Bcd
x x x Green Red
Waiting for solution.
Thanks and Best Regards UmairFor PIVOTing you can use PIVOT or CASE expression.
CASE expression PIVOT (cross tabulation):
http://www.sqlusa.com/bestpractices/training/scripts/casefunction/
You can make both CASE & PIVOT dynamic:
http://www.sqlusa.com/bestpractices2005/dynamicpivot/
Kalman Toth Database & OLAP Architect
SQL Server 2014 Database Design
New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012 -
Become our FIRST Microsoft TechNet SSRS Guru of 2014!!
Happy New Year!
Time for a fresh start!
We're looking for the first Gurus of 2014!!
This is your chance to make your mark on the Microsoft developer community.
All you have to do is add an article to TechNet Wiki from your own specialist field. Something that fits into one of the categories listed on the submissions page. Copy in your own blog posts, a forum solution, a white paper, or just something
you had to solve for your own day's work today.
Drop us some nifty knowledge, or superb snippets, and become MICROSOFT TECHNOLOGY GURU OF THE MONTH!
This is an official Microsoft TechNet recognition, where people such as yourselves can truly get noticed!
HOW TO WIN
1) Please copy over your Microsoft technical solutions and revelations to
TechNet Wiki.
2) Add a link to it on
THIS WIKI COMPETITION PAGE (so we know you've contributed)
3) Every month, we will highlight your contributions, and select a "Guru of the Month" in each technology.
If you win, we will sing your praises in blogs and forums, similar to the
weekly contributor awards. Once "on our radar" and making your mark, you will probably be
interviewed for your greatness, and maybe eventually even invited into other inner TechNet/MSDN circles!
Winning this award in your favoured technology will help us learn the active members in each community.
Feel free to ask any questions below.
More about TechNet Guru Awards
Thanks in advance!
Pete Laker
#PEJL
Got any nice code? If you invest time in coding an elegant, novel or impressive answer on MSDN forums, why not copy it over to the one and only
TechNet Wiki, for future generations to benefit from! You'll never get archived again!
If you are a member of any user groups, please make sure you list them in the
Microsoft User Groups Portal. Microsoft are trying to help promote your groups, and collating them here is the first step.We're up to 5 articles and 5 days to go!
Consume Web-Service via a SSIS Script Component by AB82
Power Pivot: Dynamic Filtering Using Slicers Post
Convert to Formulas by AB82
Power Pivot: Casting DateTime to Date in SQL Server
Source Query by Paras Doshi
How to generate
XML files in SSIS for each row of a SQL table without any custom code (No script task) by Firdous S
How to generate incrementing
numbers in SSIS using script component by Sqlsaga
Ed Price, Power BI & SQL Server Customer Program Manager (Blog,
Small Basic,
Wiki Ninjas,
Wiki)
Answer an interesting question?
Create a wiki article about it! -
Hi Team,
I need to write a SQL to cater the requirements. Below is my requirements:
pagename fieldname fieldvalue account_number consumerID
AFAccountUpdate ArrangementsBroken dfsdff 1234 1234
AFAccountUpdate ArrangementsBroken1 dfsdff 1234 1234
AFAccountUpdate ArrangementsBroken2 dfsdff 1234 1234
AFAccountUpdate ArrangementsBroken2 dfsdff 12345 12345
AFAccountUpdate ArrangementsBroken1 addf 12345 12345
Create table test_pivot_dynamic
pagename varchar(200),
fieldname Varchar(200),
fieldvalue varchar(500),
N9_Router_Account_Number bigint,
TC_Debt_Item_Reference bigint
--Input
insert into test_pivot_dynamic Values('AFAccountUpdate','ArrangementsBroken','addf',1234,1234)
insert into test_pivot_dynamic Values('AFAccountUpdate','ArrangementsBroken1','dfsdff',1234,1234)
insert into test_pivot_dynamic Values('AFAccountUpdate','ArrangementsBroken2','fder',1234,1234)
insert into test_pivot_dynamic Values('AFAccountUpdate','ArrangementsBroken2','dfdfs',12345,12345)
insert into test_pivot_dynamic Values('AFAccountUpdate','ArrangementsBroken1','dfdwe',12345,12345)
insert into test_pivot_dynamic Values('AFAccountUpdate1','Arrangements','addf',1234,1234)
insert into test_pivot_dynamic Values('AFAccountUpdate1','Test1','dfsdff',1234,1234)
--Expected output:
Select 1234,1234,'AFAccountUpdate','ArrangementsBroken','addf','ArrangementsBroken1','dfsdff','ArrangementsBroken2','fder','ArrangementsBroken2','fder'
Select 12345,12345,'AFAccountUpdate','ArrangementsBroken','addf','ArrangementsBroken1','dfdwe','ArrangementsBroken2','dfdfs'
Select 1234,1234,'AFAccountUpdate1','Arrangements','addf','Test1','dfsdff'
so basically we have to pivot and dynamic sql and insert the expected output to a common table which will have all the required fields
Thanks,Ram.
Please don't forget to Marked as Answer if my post solved your problem and use Vote As Helpful if a post was useful. It will helpful to other users.This should give you what you're looking for
SELECT N9_Router_Account_Number,TC_Debt_Item_Reference,PageName,
MAX(CASE WHEN SEQ = 1 THEN fieldname END) AS fieldname1,
MAX(CASE WHEN SEQ = 1 THEN fieldvalue END) AS fieldvalue1,
MAX(CASE WHEN SEQ = 2 THEN fieldname END) AS fieldname2,
MAX(CASE WHEN SEQ = 2 THEN fieldvalue END) AS fieldvalue2,
MAX(CASE WHEN SEQ = 3 THEN fieldname END) AS fieldname3,
MAX(CASE WHEN SEQ = 3 THEN fieldvalue END) AS fieldvalue3,
MAX(CASE WHEN SEQ = 4 THEN fieldname END) AS fieldname4,
MAX(CASE WHEN SEQ = 4 THEN fieldvalue END) AS fieldvalue4
FROM
SELECT *,ROW_NUMBER() OVER (PARTITION BY N9_Router_Account_Number,TC_Debt_Item_Reference,PageName ORDER BY PageName) AS SEQ,*
FROM test_pivot_dynamic
)t
GROUP BY N9_Router_Account_Number,TC_Debt_Item_Reference,PageName
To make it dynamic see
http://www.beyondrelational.com/modules/2/blogs/70/posts/10791/dynamic-crosstab-with-multiple-pivot-columns.aspx
Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs -
Dynamically selecting values for filter in power pivot
Hi,
I am creating a power pivot report. I want the values of its filters to be set dynamically based on certain critreria. For Example, if some one changes the Iteration Path then the range of dates should change automatically to Iteration start date -
Itearation End Date.
Is there any way to set filter values based on some calculation.
Any help in this regard will be highly appreciated.
Thanks,
Bhawna.
Bhawna AggarwalCheck out the Event-In-Progress pattern as described here:
http://cwebbbi.wordpress.com/2013/06/13/a-new-events-in-progress-dax-pattern/
basically you need to create a separate measure which to do the specific filtering for you
hth,
gerhard
Gerhard Brueckl
blogging @ http://blog.gbrueckl.at
working @ http://www.pmOne.com -
How to Handle Dynamic Pivoting with a single SQL?
I was searching for a single SQL who can dynamically understands the pivoting members in the data, I saw several ways of doing Pivoting depending on the version, some are really hard to understand but just two options upto now seams to be flexable enough to do dynamic pivoting, right?
1- For this option you have to write PL/SQL block to build up the dynamic single SQL query, I also find this approach very easy to understand. :)
http://asktom.oracle.com/pls/asktom/f?p=100:11:0::NO::P11_QUESTION_ID:766825833740
2- 11.1 's PIVOT new feature with PIVOT XML and ANY clause, a SINGLE SQL and easy to understand but returns XMLTYPE data, another step to parse to produce the report is needed.
http://www.oracle-developer.net/display.php?id=506
Below is a 10g Model Clause example, but here instead of pivoting by A1-A2-A3 staticly I want to have these values by a distinc subquery for example;
create table test(id varchar2(2), des varchar2(4), t number);
INSERT INTO test values('A','a1',12);
INSERT INTO test values('A','a2',3);
INSERT INTO test values('A','a3',1);
INSERT INTO test values('B','a1',10);
INSERT INTO test values('B','a2',23);
INSERT INTO test values('C','a3',45);
commit;
SELECT * FROM test;
ID DES T
A a1 12
A a2 3
A a3 1
B a1 10
B a2 23
C a3 45
select distinct i, A1, A2, A3
from test c
model
ignore nav
dimension by(c.id i,c.des d)
measures(c.t t, 0 A1, 0 A2, 0 A3)
rules(
A1[any,any] = t[cv(i),d = 'a1'],
A2[any,any] = t[cv(i),d = 'a2'],
A3[any,any] = t[cv(i),d = 'a3']
I A1 A2 A3
C 0 0 45
B 10 23 0
A 12 3 1 Any advice is appreciated, thank you.Hi,
You can do dynamic SQL in SQL*Plus, also.
[Thid thread|http://forums.oracle.com/forums/thread.jspa?messageID=2744039�] shows how to pivot a table with a dynamic number of columns. -
Dynamic SQL PIVOT not producing output?
Hey all,
Find my source code with test data scripts below. Since my production system is not connected to the inet, I had to type this
"by hand" as it were, so please pardon any mispellings. I have no way to test on my inet-enabled PC before posting.
Anyways, here's my issue: if you run the below code as PL/SQL script, it runs fine but it produces NO output (it should display a
grid of data). That is my dilemma. How to get my dynamic pivot to actually SHOW the data. So I've been experimenting with
EXECUTE IMMEDIATE, but when I use that syntax, it blows up with the error:
PLS-00321: expression 'TMPTABLE' is inappropriate as the left hand side of an assignment statement
I have provide the lines below which cause the error, but they are commented out so you can see it runs fine the 1st way (yet
displays no data) and blows up the 2nd way. I would appreciate your insights.
Thanks
DROP TABLE table1;
DROP TABLE table2;
DROP TABLE datetable;
CREATE TABLE table1
TIME_STAMP TIMESTAMP(6) DEFAULT systimestamp NOT NULL,
Id VARCHAR2(50 BYTE) NOT NULL
CREATE TABLE table2
NAME VARCHAR2(50 BYTE),
Id VARCHAR2(50 BYTE) NOT NULL
CREATE TABLE datetable
YEAR_WEEK VARCHAR2(7 BYTE),
WEEK_START_DATE DATE
INSERT INTO table1 VALUES (to_date(‘05/30/2011’,’MM/DD/YYYY’),’1’);
INSERT INTO table1 VALUES (to_date(‘05/31/2011’,’MM/DD/YYYY’),’1’);
INSERT INTO table1 VALUES (to_date(‘06/01/2011’,’MM/DD/YYYY’),’1’);
INSERT INTO table1 VALUES (to_date(‘06/02/2011’,’MM/DD/YYYY’),’1’);
INSERT INTO table1 VALUES (to_date(‘06/03/2011’,’MM/DD/YYYY’),’2’);
INSERT INTO table1 VALUES (to_date(‘06/04/2011’,’MM/DD/YYYY’),’2’);
INSERT INTO table1 VALUES (to_date(‘06/05/2011’,’MM/DD/YYYY’),’2’);
INSERT INTO table1 VALUES (to_date(‘06/07/2011’,’MM/DD/YYYY’),’2’);
INSERT INTO table1 VALUES (to_date(‘06/08/2011’,’MM/DD/YYYY’),’1’);
INSERT INTO table1 VALUES (to_date(‘06/09/2011’,’MM/DD/YYYY’),’1’);
INSERT INTO table1 VALUES (‘Bob’,’1’);
INSERT INTO table1 VALUES (‘Gary’,’2’);
INSERT INTO table1 VALUES (‘2011-21’,to_date(‘05/23/2011’,’MM/DD/YYYY’));
INSERT INTO table1 VALUES (‘2011-22’,to_date(‘05/30/2011’,’MM/DD/YYYY’));
INSERT INTO table1 VALUES (‘2011-23’,to_date(‘06/06/2011’,’MM/DD/YYYY’));
INSERT INTO table1 VALUES (‘2011-24’,to_date(‘06/13/2011’,’MM/DD/YYYY’));
DECLARE
sql_txt VARCHAR2 (32767);
--keep the below commented for the 1st test, uncomment for 2nd test
--TYPE tmpTable IS TABLE OF VARCHAR2(100) INDEX BY BINARY_INTEGER;
BEGIN
sql_txt :=
Q'{WITH got_dates AS
SELECT b.name,
COUNT(*) AS Responded,
iso.week_start_date AS week_start_date
FROM
table1 a INNER JOIN table2 b ON
(a.id = b.id) INNER JOIN datetable iso ON
((case when to_char(a.time_stamp, 'IW')='53' then to_char(cast(to_char(a.time_stamp, 'IYYY') as int)+1) || '-01' else to_char(a.time_stamp, 'IYYY-IW') end) = iso.year_week)
WHERE
(a.time_stamp >= sysdate-30)
GROUP BY
iso.week_start_date,
b.name
SELECT *
FROM got_dates
PIVOT (
SUM (Responded) FOR week_start_date IN (
FOR d_rec IN (
WITH possible_dates AS
SELECT SYSDATE + 1 - LEVEL AS time_stamp
FROM DUAL
CONNECT BY LEVEL <= 31
SELECT DISTINCT 'DATE '''
|| TO_CHAR ( c.week_start_date
, 'YYYY-MM-DD'
|| ''' AS '
|| TO_CHAR ( c.week_start_date
, 'mon_dd_yyyy'
|| CASE
WHEN DENSE_RANK () OVER (ORDER BY c.week_start_date) > 1
THEN ','
END AS txt
FROM possible_dates p
INNER JOIN datetable c ON c.year_week =
CASE
WHEN TO_CHAR ( p.time_stamp, 'IW') = '53'
THEN TO_CHAR (cast(TO_CHAR(p.time_stamp,'IYYY') AS int)+1) || '-01'
ELSE TO_CHAR ( p.time_stamp, 'IYYY-IW')
END
ORDER BY txt DESC
LOOP
sql_txt := sql_txt || ' ' || d_rec.txt;
END LOOP;
sql_txt := sql_txt || ') )';
--keep the below commented for the 1st test, uncomment for 2nd test. also, comment out the 2nd EXECUTE IMMEDIATE (only 1 at a time should be uncommented)
--EXECUTE IMMEDIATE sql_txt BULK COLLECT INTO tmpTable;
EXECUTE IMMEDIATE sql_txt;
END;Edited by: user8825851 on Oct 6, 2011 2:12 PMHi,
user8825851 wrote:
Find my source code with test data scripts below. Since my production system is not connected to the inet, I had to type this
"by hand" as it were, so please pardon any mispellings. I have no way to test on my inet-enabled PC before posting. Install an Oracle database on your PC. It's free and it's not difficult. if you're going to use this forum, whatever time you have to invest in it will pay off within a week.
http://www.oracle.com/technetwork/database/enterprise-edition/downloads/index.html
Anyways, here's my issue: if you run the below code as PL/SQL script, it runs fine but it produces NO output (it should display a
grid of data)...In PL/SQL, you always have to SELECT into something.
One simple way is to open a cursor. Before running the PL/SQL code, declare a bind variable for the cursor:
VARIABLE c REFCURSOR
-- And while you're at it, do this, too
SET SERVEROUTPUT ONIn the PL/SQL code, use an OPEN statement in place of EXECUTE IMMEDIATE:
... dbms_output.put_line (sql_txt); -- For debugging only
-- EXECUTE IMMEDIATE sql_txt; -- Don't do this
OPEN :c FOR sql_txt; -- Do this instead
END;
/After the PL/SQL is finsihed, you can use PRINT to see the results:
PRINT :cIn this case, you'll get an error message because the dynamic code is incorrect. That's what the call to put_line is for: to show exactly what you're running. If there's a problem, you can examine the output, or copy it into a script, edit it and debug it.
In this case, you'll see that the dynamic SQL ends with:
PIVOT (
SUM (Responded) FOR week_start_date IN (
) )The part that's supposed to be dynamic is missing. That part is supposed to be written inside the d_rec cursor loop, but d_rec is returning no rows. That's because of the join condition:
INNER JOIN datetable c ON c.year_week =
CASE
WHEN TO_CHAR ( p.time_stamp, 'IW') = '53'
THEN TO_CHAR (cast(TO_CHAR(p.time_stamp,'IYYY') AS int)+1) || '-01'
ELSE TO_CHAR ( p.time_stamp, 'IYYY-IW')
END With the given sample data, p.time_stamp is producing values between '2011-36' and '2011-40', but the values in c.week are
INSERT INTO table1 VALUES (‘2011-21’,to_date(‘05/23/2011’,’MM/DD/YYYY’));
INSERT INTO table1 VALUES (‘2011-22’,to_date(‘05/30/2011’,’MM/DD/YYYY’));
INSERT INTO table1 VALUES (‘2011-23’,to_date(‘06/06/2011’,’MM/DD/YYYY’));
INSERT INTO table1 VALUES (‘2011-24’,to_date(‘06/13/2011’,’MM/DD/YYYY’));(I assume you meant "INSERT INTO *datetable* " above.)
Perhaps you meant LEFT OUTER JOIN instead of INNER JOIN in d_rec. -
How change the graph dynamically based on pivot table.
Hi,
My Report having pivot table and bar chart. Organization Name column set as pivot table prompts in pivot table.So Organization Name is appear as dropdown list.If i choose the diffrent Organization Names the pivot table data is according to the Organization Name but no changes in chart.How change the Graph dynamically based on pivot table.
Please help on this.ok.I created pivot table with 4 columns and created chart using pivot table chart options but all 4 columns are displaying chart.But I need only 2 column in chart ..unable to edit the only chart in pivot table.Please help on this.Thank you..
-
Dynamic data source in Excel Pivot Table
Hello there,
I am trying to have dynamic data source in pivot table using INDIRECT but getting the error "Reference not valid". Here is how I setup the reference:
Named range: ConsolLink = "'R:\Root\Sub1\Sub2\Consol File.xlsm'!Source_OpexConsol"
"Source_OpexConsol" is defined in the source file as a dynamic name using offset formula.
In the pivot data source, I have tried "=INDIRECT(ConsolLink)" as the data source but that does not work.
I have also tried using INDIRECT in ConsolLink and just referencing "ConsolLink" as the data source. That does not work either.
I am not using Power Pivot. Appreciate it if someone can help.
Thanks.If it is open, then try
Named range: ConsolLink = Range("Consol File.xlsm'!Source_OpexConsol")
And if it is not currently open, then try
Dim W As Workbook
Set W = Workbooks.Open("R:\Root\Sub1\Sub2\Consol
File.xlsm")
Named range: ConsolLink =
Range("Consol File.xlsm'!Source_OpexConsol")
W.Close False -
Setting Column Names in Dynamic Pivot Query
Hi all,
I'm having trouble setting column names in a dynamic pivot query and was wondering if someone could please help me figure out what I need to do.
To help you help me, I've setup an example scenario in my hosted account. Here's the login info for my hosted site at [http://apex.oracle.com]
Workspace: MYHOSTACCT
Username : DEVUSER1
Password : MYDEVACCTAnd, here is my test application info:
ID : 42804
Name : dynamic query test
Page : 1
Table 1: PROJECT_LIST (Alias = PL... Listing of Projects)
Table 2: FISCAL_YEAR (Alias = FY... Lookup table for Fiscal Years)
Table 3: PROJECT_FY (Alias = PF... Intersection table containing project fiscal years)
Table 4: PROJECT_FY_HEADCOUNT (Alias = PFH... Intersection table containing headcount per project and fiscal year)Please forgive the excessive normalization for this example, as I wanted to keep the table structure similar to my real application, which has much more going on.
In my sample, I have the "Select Criteria" region, where the user specifies the project and fiscal year range that he or she would like to report. Click the Search button, and the report returns the project headcount in a pivoted fashion for the fiscal year range specified.
I've got it working using a hard-coded query, which is displayed in the "Hardcoded Query" region. In this query, I basically return all years, and set conditions on each column which determines whether that column should be displayed or not based on the range selected by the user. While this works, it is not ideal, as there could be many more fiscal years to account for, and this is not very dynamic at all. Anytime a fiscal year is added to the FISCAL_YEAR table, I'd have to update this page.
So, after reading all of the OTN SQL pivot forums and "Ask Tom" pivot thread, I've been able to create a second region labeled "Dynamic Query" in which I've created a dynamic query to return the same results. This is a much more savvy solution and works great; however, the column names are generic in the report.
I had to set the query to parse at runtime since the column selection list is dynamic, which violates SQL rules. Can anyone please help me figure out how I can specify my column names in the dynamic query region to get the same column values I'm getting in the hardcoded region?
Please let me know if you need anymore information, and many thanks in advance!
MarkHi Tony,
Thanks so much for your response. I've had to study up on the dbms_sql package to understand your function... first time I've used it. I've fed my dynamic query to your function and see that it returns a colon delimited list of the column names; however, I think I need a little more schooling on how and where exactly to apply the function to actually set the column names in APEX.
From my test app, here is the code for my dynamic query. I've got it in a "PL/SQL function body returning sql query" region:
DECLARE
v_query VARCHAR2(4000);
v_as VARCHAR2(4);
v_range_from NUMBER;
v_range_to NUMBER;
BEGIN
v_range_from := :P1_FY_FROM;
v_range_to := :P1_FY_TO;
v_query := 'SELECT ';
-- build the dynamic column selections by looping through the fiscal year range.
-- v_as is meant to specify the column name as (FY10, FY11, etc.), but it's not working.
FOR i IN v_range_from.. v_range_to LOOP
v_as := 'FY' || SUBSTR(i, 3, 4);
v_query := v_query || 'MAX(DECODE(FY_NB,' || i || ',PFH_HEADCOUNT,0)) '
|| v_as || ',';
END LOOP;
-- add the rest of the query to the dynamic column selection
v_query := rtrim(v_query,',') || ' FROM ('
|| 'SELECT FY_NB, PFH_HEADCOUNT FROM ('
|| 'SELECT FY_ID, FY_NB FROM FISCAL_YEAR) A '
|| 'LEFT OUTER JOIN ('
|| 'SELECT FY_ID, PFH_HEADCOUNT '
|| 'FROM PROJECT_FY_HEADCOUNT '
|| 'JOIN PROJECT_FY USING (PF_ID) '
|| 'WHERE PL_ID = ' || :P1_PROJECT || ') B '
|| 'ON A.FY_ID = B.FY_ID)';
RETURN v_query;
END;I need to invoke GET_QUERY_COLS(v_query) somewhere to get the column names, but I'm not sure where I need to call it and how to actually set the column names after getting the returned colon-delimited list.
Can you (or anyone else) please help me get a little further? Once again, feel free to login to my host account to see it first hand.
Thanks again!
Mark -
Dynamic Hyperlinks In Pivot Table
Hi All,
I'm trying to make a column in a pivot table have a hyperlink based on data, but it doesn't seem to work. Funny thing is I can do exactly the same thing with just a normal table and it works fine.
Just putting {PAGE_URL} for the hyperlink address in word, where PAGE_URL is a column in my query.
Any ideas?
Thanks
MattHere is an example for dynamic PIVOT:
http://www.sqlusa.com/bestpractices2005/dynamicpivot/
You can also apply dynamic columns in SSRS:
http://www.sqlservercentral.com/Forums/Topic1497220-2799-1.aspx#bm1497636
http://social.msdn.microsoft.com/Forums/sqlserver/en-US/b5dbd178-1532-478f-90d3-b6354a561240/ssrs-dynamic-columns?forum=sqlreportingservices
Kalman Toth Database & OLAP Architect
IPAD SELECT Query Video Tutorial 3.5 Hours
New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012
Maybe you are looking for
-
Create Vendor Master Record from HR Master Record
Hi All, I am running PRAA Transaction Code, While running I am getting this Error. Employee for whom a vendor master record already exists. Personnel Number missing in company code segment. Then I went to SM35 but did not found any batch. Please can
-
Mail problems-can't click reply and more
When I first got my Imac I transfer all data from my older machine running OS X. Mail worked just fine for a couple of weeks then it started having the same problem I have now. I tried rebuilding and throwing away the preference but no luck so I gave
-
Process chains- different data loads at different points of time
hi friends i want to load master data at 4am and then i want to load transaction data at 4:25 am how can i achieve this by using process chains to load other datas also at different times and where we h
-
I would like to have an app to act as a To-Do list that has cross-platform of iSO and Android. Toodledo is one choice for me but all the apps do not have the sort key of completed dates in reverse order selection. If it does not need internet conne
-
How do I add vimeo as a favorite to upload to in the sharing groups on the dock? Are my only choices youtube, flicker, picaasa and facebook? I'd rather use vimeo. Thanks.