Using PIVOT query in ViewObject
I was wondering if it's possible to create a ViewObject based on a query with PIVOT. The query looks like
SELECT * FROM myTable
PIVOT ( SUM(myTable.VALUE) FOR TIME IN ('2010', '2011'));
And I get the following error:
ORA-00907: missing right parenthesis.
The query works in SQL Developer.
JDev 11.1.1.6.0
My working query in SQL Developer is
SELECT * FROM (
SELECT TIME, VALUE
FROM MYTABLE
WHERE CODE = :pCode
PIVOT (
SUM(VALUE) FOR TIME IN (2009)
with TIME as NUMBER.
But if I copy it in a ViewObject I get the right parenthesis error. The '^' points to the T of PIVOT, not sure the location is accurate. My goal is then to use that VO with getEstimatedRowCount, executeQuery and also apply some ViewCriteria on it. I never worked with PIVOT query, so I am not sure if it makes a difference on what I can do with the VO.
Similar Messages
-
SQL Query without using Pivot...
Hi Guys,
Need help with a query... I think pivot table is the way to go but don't wanna to use it as it is not supported in Oracle 10g.
Sample data set...
Part
Section
A001
AC
A001
AY
A001
AN
A001
AX
A015
AC
A015
AR
A007
AC
A008
AN
A008
AX
A008
AE
A008
AT
A008
AY
Required output... (Please note that I cannot hard code the Section column as the data is dynamic)
Part
AC
AY
AN
AX
AR
AE
AT
A001
Y
Y
Y
Y
A015
Y
Y
A007
Y
A008
Y
Y
Y
Y
Y
Can you help me out with this without using pivot tables?
Thanks,
NapsterHi Napster, Try this
select part,
max(decode(section,'AC','Y',NULL)) AC,
max(decode(section,'AY','Y',NULL)) AY,
max(decode(section,'AN','Y',NULL)) AN,
max(decode(section,'AX','Y',NULL)) AX,
max(decode(section,'AC','Y',NULL)) AC,
max(decode(section,'AR','Y',NULL)) AR,
max(decode(section,'AT','Y',NULL)) AT
from sple group by part
SQL> /
Output will be
PART A A A A A A A
A001 Y Y Y Y Y
A007 Y Y
A008 Y Y Y Y
A015 Y Y Y -
With out using pivot function need a Query
Hi
I am having table which has 7 columns
data in table:
ID,Region,area, year-month, sales_target, actual_sales,
1, abc, xyz, 200907, 1000, 500
2, abc, pqr, 200908, 2000, 1500
3, mnr, xyz, 200907, 3000, 2000
I need the data in year and month with out using pivot funtion
intial
region, area, jul, aug, sep, oct .......jun
abc, xyz, 1000,0, 0, 0... 0
actual
region, area, jul, aug, sep, oct .......jun
abc, xyz, 500, 0, 0, 0... 0ThanksHere it is
with d as ( select 1 ID, 'abc' Region, 'xyz' area, 200907 yearmonth, 1000 sales_target, 500 actual_sales from dual
union all select 2, 'abc', 'pqr', 200908, 2000, 1500 from dual
union all select 3, 'mnr', 'xyz', 200907, 3000, 2000 from dual
select region, area,
max(case extract(month from to_date(yearmonth,'yyyymm')) when 7 then sales_target
else 0 end ) TGT_JUL
max(case extract(month from to_date(yearmonth,'yyyymm')) WHEN 8 then sales_target
else 0 end ) TGT_AUG
max(case extract(month from to_date(yearmonth,'yyyymm')) WHEN 9 then sales_target
else 0 end ) TGT_SEP
from d
group by region, area
REG ARE TGT_JUL TGT_AUG TGT_SEP
abc pqr 0 2000 0
mnr xyz 3000 0 0
abc xyz 1000 0 0You can copy and replicate the results for another one - actual_sales. -
How to pivot using pivot clause of sqlserver 2005 for three values
Dear all
Is it possible to formulate the query using pivote clause of sqlserver 2005.
( Table name is) BridgeHawra
ReportDate, , Pole, DiameterCost,Flag,OuterDiaCost
01 jan 2014, ,1 , 4.5 ,yes,6
01 jan 2014, ,2 , 4.5 ,no,6
01 jan 2014, ,3 , 5.5 ,no,6
02 jan 2014, ,4 , 5.5 ,no,5.9
02 jan 2014, ,5 , 5.5 ,no,6
1)Pole Col will have unique value.
o2)One pole will have one DiameterCost, but n number of DiameterCost can be there.
I have to show a report which should show , count of poles and cost(DiameterCost* pole count of the day of each DiameterCost) for each date and DiameterCost.
as following
DateOfReport , PoleCountofDiameterCost4.5, DiameterCost4.5, PoleCountOfDiameterCost5.5,DiameterCost5.5
01 jan 2014 , 2
,(2*4.5) ,1
,(1*5.5)
02 jan 2014 , 0/null ,0/null
,2
,(2*5.5)
yours sincerelyYes it is possible though you need to use dynamic pivot technique. Dynamic pivot allow you to select/display column names dynamically.
Below example does not use dynamic pivot,
--create table #temp(ReportDate datetime,Pole int, DiameterCost decimal(5,2),Flag varchar(3),OuterDiaCost decimal(5,2))
--insert into #temp values('01 jan 2014',1,4.5,'yes',6)
--insert into #temp values('01 jan 2014',2,4.5,'no',6)
--insert into #temp values('01 jan 2014',3,5.5,'no',6)
--insert into #temp values('02 jan 2014',4,5.5,'no',5.9)
--insert into #temp values('02 jan 2014',5,5.5,'no',6)
;with cte as (
select ReportDate,
DiameterCost * PoleCount as DiameterCost,
PoleCount ,
'PoleCountofDiameterCost'+cast(DiameterCost as varchar) column1,
'DiameterCost'+cast(DiameterCost as varchar) column2
from (
select ReportDate,DiameterCost,Count(Pole) as PoleCount from #temp
group by ReportDate,DiameterCost
) x
),cte1 as (
select * from cte
pivot( max(PoleCount) for column1 in ([PoleCountofDiameterCost4.50],[PoleCountofDiameterCost5.50])
) pvt
pivot( max(DiameterCost) for column2 in ([DiameterCost4.50],[DiameterCost5.50])
) pvt1
select ReportDate,
Max([PoleCountofDiameterCost4.50]) [PoleCountofDiameterCost4.50],
Max([DiameterCost4.50]) [DiameterCost4.50],
Max([PoleCountofDiameterCost5.50]) [PoleCountofDiameterCost5.50],
Max([DiameterCost5.50]) [DiameterCost5.50] from cte1
group by ReportDate
Regards, RSingh -
Getting counts and divide by sum in a single Pivot query
Hi,
I have a pivot query which gives the counts of all codes. I also have to divide the count with the total in the same query.
e.g
col1 col2 col3
error_1 05-Jun-2012 parts
error_1 05_june_2012 parts
error_1 04_june_2012 consumables
error_2 04_june_2012 consumables
error_3 03_june_2012 parts
.Now the output should have the counts/divided by sum multiplied by 100. Basically, the percentage.
output will be something like
error June-2012 May-2012 Feb-2012 .... headers
error_1 60% 0 % 0%
error_2 20% 0 0%
error_3 20% 0% 0%Any suggestions please?
Thanks,
Sunwith
t1 as
(select 'error_1' col1,trunc(sysdate) - 1 col2 from dual union all
select 'error_1',trunc(sysdate) - 1 from dual union all
select 'error_1',trunc(sysdate) + 30 from dual union all
select 'error_2',trunc(sysdate) + 31 from dual union all
select 'error_3',trunc(sysdate) - 2 from dual union all
select 'error_3',trunc(sysdate) + 30 from dual union all
select 'error_1',trunc(sysdate) - 3 from dual union all
select 'error_2',trunc(sysdate) - 2 from dual union all
select 'error_3',trunc(sysdate) + 30 from dual union all
select 'error_4',trunc(sysdate) - 6 from dual
select col1,
count(case to_char(col2,'mon') when 'jul' then 1 end) one,
100 * ratio_to_report(count(case to_char(col2,'mon') when 'jul' then 1 end)) over () x,
count(case to_char(col2,'mon') when 'jun' then 1 end) two,
100 * ratio_to_report(count(case to_char(col2,'mon') when 'jun' then 1 end)) over () y
from t1
group by col1
order by col1Regards
Etbin
Edited by: Etbin on 8.6.2012 14:15
used next month to keep english and slovenian 'mon' the same ;) -
Help in Pivot Query- To change the column data to rows data!
Hello Gurus -
I have to change the row to Column -
When i use the query -
select NVL (T2.NAME, ' Grand Total') AS State,count(T2.NAME) as Total
from Defect T1,statedef T2,repoproject T3
WHERE T1.STATE=T2.ID AND T1.repoproject = T3.dbid AND T3.name like '%Compass Juice' GROUP BY ROLLUP (T2.NAME)
Then i have got the following data -
STATE TOTAL
Analysis 17
Closed 1302
Development 9
Duplicate 24
Failed 2
OnHold 4
Opened 146
QA 1
ReadyForQA 1
Withdrawn 335
Grand Total 1841
But i want the data in following format -
State Analysis Closed Development Duplicate Failed OnHold Opened QA ReadyForQA Withdrawn GrandTotal
Total 17 1302 9 24 2 4 146 1 1 335 1841
Kindly help me with this. I searched the forum and saw the usage of Max and NVL, Decode but i am unable to understand it to use in my query. kindly help me with this.Hi,
In 11g you can use pivot.
[http://www.oracle.com/technology/pub/articles/oracle-database-11g-top-features/11g-pivot.html]
example
SQL> desc customers
Name Null? Type
CUST_ID NUMBER(10)
CUST_NAME VARCHAR2(20)
STATE_CODE VARCHAR2(2)
TIMES_PURCHASED NUMBER(3)
When this table is selected:
select cust_id, state_code, times_purchased
from customers
order by cust_id;
The output is:
CUST_ID STATE_CODE TIMES_PURCHASED
1 CT 1
2 NY 10
3 NJ 2
4 NY 4
... and so on ...
Note how the data is represented as rows of values: For each customer, the record shows the customer's home state and how many times the customer purchased something from the store. As the customer purchases more items from the store, the column times_purchased is updated.
Now consider a case where you want to have a report of the purchase frequency each state�that is, how many customers bought something only once, twice, thrice and so on, from each state. In regular SQL, you can issue the following statement:
select state_code, times_purchased, count(1) cnt
from customers
group by state_code, times_purchased;
Here is the output:
ST TIMES_PURCHASED CNT
CT 0 90
CT 1 165
CT 2 179
CT 3 173
CT 4 173
CT 5 152
... and so on ...
This is the information you want but it's a little hard to read. A better way to represent the same data may be through the use of crosstab reports, in which you can organized the data vertically and states horizontally, just like a spreadsheet:
Times_purchased
CT NY NJ ... and so on ...
1 0 1 0 ...
2 23 119 37 ...
3 17 45 1 ...
... and so on ...
Prior to Oracle Database 11g, you would do that via some sort of a decode function for each value and write each distinct value as a separate column. The technique is quite nonintuitive however.
Fortunately, you now have a great new feature called PIVOT for presenting any query in the crosstab format using a new operator, appropriately named pivot. Here is how you write the query:
select * from (
select times_purchased, state_code
from customers t
pivot
count(state_code)
for state_code in ('NY','CT','NJ','FL','MO')
order by times_purchased
Here is the output:
. TIMES_PURCHASED 'NY' 'CT' 'NJ' 'FL' 'MO'
0 16601 90 0 0 0
1 33048 165 0 0 0
2 33151 179 0 0 0
3 32978 173 0 0 0
4 33109 173 0 1 0
... and so on ... -
Dynamic SQL and Pivot Query in 11G
Hello all,
I am using APEX and 11G I am trying to create a report based on the results of a pivot query. Below is the code to build the query string. The :P4_EPSB_PERIOD_HOLD holds data like (SEP-08') for example.
declare
q varchar2(4000);
begin
q:=q ||' select * FROM';
q:=q ||' ( ';
q:=q ||' select segment2, ';
q:=q ||' accounted_dr, ';
q:=q ||' period_name ';
q:=q ||' from gl_je_lines a, ';
q:=q ||' gl_code_combinations b';
q:=q ||' where b.code_combination_id = a.code_combination_id';
q:=q ||' and segment2 >= :P4_EPSB_OBJECT_FROM';
q:=q ||' and segment2 <= :P4_EPSB_OBJECT_TO';
q:=q ||' and period_name IN :P4_EPSB_PERIOD_HOLD';
q:=q ||' and segment4 >= :P4_EPSB_LOCATION_FROM';
q:=q ||' and segment4 <= :P4_EPSB_LOCATION_TO';
q:=q ||' )';
q:=q ||' PIVOT';
q:=q ||' (';
q:=q ||' sum(accounted_dr)';
q:=q ||' for period_name IN :P4_EPSB_PERIOD_HOLD';
q:=q ||' )';
return q;
end;
I get the missingfailed to parse SQL query:
ORA-00906: missing left parenthesis
If I print the sql statement that the query generates, I get the following code, which, if the varaibles are hard-coded, works fine.
select * FROM ( select segment2, accounted_dr, period_name from gl_je_lines a, gl_code_combinations b where b.code_combination_id = a.code_combination_id and segment2 >= :P4_EPSB_OBJECT_FROM and segment2 <= :P4_EPSB_OBJECT_TO and period_name IN :P4_EPSB_PERIOD_HOLD and segment4 >= :P4_EPSB_LOCATION_FROM and segment4 <= :P4_EPSB_LOCATION_TO ) PIVOT ( sum(accounted_dr) for period_name IN :P4_EPSB_PERIOD_HOLD )
Any advice as to how to tackle this would be most welecome and appreciated.
ThanksP4_EPSB_PERIOD_HOLDcome with single quotes? like 'SEP-08' or SEP-08
-
11G Pivot Query with Oracle EBS
Hello all,
We are trying to use the 11G pivot query function with data from Oracle E-Business Suite. We have an 11G database installed with our Oracle APEX. We cannot seem to get the pivot function to work. At a glance, would anyone be able to see any glaring errors in our syntax. I am not certain it is possible to provide test data so...
We are trying to have column headings with the Period Names SEP-08 OCT-08 NOV-08, with rows of segment2 007751 and accounted_dr as the dataset.
When we run the sql we get an error ORA-00904: "PERIOD_NAME": invalid identifier.
Any help or insight would be greatly appreciated.
select * from (
select segment2, accounted_dr, period_name
from gl_je_lines a, gl_code_combinations b
where b.code_combination_id = a.code_combination_id
and segment2 = '007751')
pivot
sum(accounted_dr)
for period_name in ('SEP-08','OCT-08','NOV-08')
group by segment2, period_namelilhelp wrote:
Hello all,
We are trying to use the 11G pivot query function with data from Oracle E-Business Suite. We have an 11G database installed with our Oracle APEX. We cannot seem to get the pivot function to work. At a glance, would anyone be able to see any glaring errors in our syntax. I am not certain it is possible to provide test data Why not?
>
We are trying to have column headings with the Period Names SEP-08 OCT-08 NOV-08, with rows of segment2 007751 and accounted_dr as the dataset.
When we run the sql we get an error ORA-00904: "PERIOD_NAME": invalid identifier.
Any help or insight would be greatly appreciated.
select * from (
select segment2, accounted_dr, period_name
from gl_je_lines a, gl_code_combinations b
where b.code_combination_id = a.code_combination_id
and segment2 = '007751')
pivot
sum(accounted_dr)
for period_name in ('SEP-08','OCT-08','NOV-08')
group by segment2, period_nameDon't use GROUP BY. When you use PIVOT, the grouping is implied by what is in the PIVOT clause and what is not.
Try this:
select *
from (
select segment2
, accounted_dr
, period_name
from gl_je_lines a
, gl_code_combinations b
where b.code_combination_id = a.code_combination_id
and segment2 = '007751'
pivot (
sum (accounted_dr)
for period_name in ('SEP-08','OCT-08','NOV-08')
;which is just your posted query without the GROUP BY clause. -
How to find bottleneck in pivot query
I have the following table and query I am running against that table.
CREATE TABLE StagingTable(
DateKey int NOT NULL,
VersionNumber smallint NOT NULL,
SetID varchar(10) NULL,
ClassID char(5) NULL,
VariableName varchar(50) NULL,
VariableDescription varchar(255) NULL,
PeriodNumber int NULL,
PeriodData decimal(18, 6) NULL,
Column1 varchar(50) NULL,
Column2 varchar(50) NULL,
Column3 varchar(50) NULL,
Column4 varchar(50) NULL,
Column5 int NULL,
Column6 varchar(25) NULL,
Column7 int NULL,
Column8 int NULL,
Column9 varchar(50) NULL,
Column10 varchar(50) NULL,
Column11 varchar(50) NULL,
Column12 int NULL,
RowNumber int NULL
GO
WITH cte as (
SELECT
DateKey ,
VersionNumber ,
SetID ,
ClassID ,
VariableName ,
PeriodNumber ,
PeriodData
from StagingTable
SELECT
DateKey ,
VersionNumber ,
SetID ,
ClassID ,
VariableName,
[0], [1], [2], [3], ,,,, [360]
from cte
pivot (SUM(PeriodData)
FOR PeriodNumber IN (
[0], [1], [2], [3], ..., [360]
) as pvt;
CREATE UNIQUE NONCLUSTERED INDEX IX_StagingTable ON dbo.StagingTable
DateKey,
VersionNumber,
SetId,
ClassID,
VariableName,
PeriodNumber
INCLUDE ([PeriodData])
I have about 5 million rows in StageTable and the pivot query returns 32,000 rows. It takes about 3 and a half minutes to run this query, whether I am outputting the results to the results window in SSMS or selecting into a new table.
I checked the execution plan for this query (outputting to results window) and the only operation that takes any time is the non-clustered index scan (84% with Stream aggregate showing 14%).
Here are the things I compared this to. I ran a select from this table using just the columns in the index. The results returned in less than one minute and as expected the most expensive operation (100%) was the non-clustered index scan.
By the way, a select into returned almost immediately.
If I take the pivot results (after a select into) and create a new table by select into, it takes almost no time for the query to finish.
I did an estimated execution plan on these three queries (where PivotTable is a dump of the pivot query into a heap):
WITH cte as (
SELECT
DateKey ,
VersionNumber ,
SetID ,
ClassID ,
VariableName ,
PeriodNumber ,
PeriodData
from StagingTable
SELECT
DateKey ,
VersionNumber ,
SetID ,
ClassID ,
VariableName,
[0], [1], [2], [3], ,,,, [360]
from cte
pivot (SUM(PeriodData)
FOR PeriodNumber IN (
[0], [1], [2], [3], ..., [360]
) as pvt;
SELECT * from PivotTable;
SELECT
DateKey ,
VersionNumber ,
SetID ,
ClassID ,
VariableName ,
PeriodNumber ,
PeriodData
from StagingTable;
The first query (pivot query) had a cost of 41%, the second 25% (select pivottable) and the third 34% (select base table). These are nowhere close to the ratios of the amount of time that it takes to run these queries (pivot query 3.5 minutes,
select PivotTable 5 seconds and select base table almost one minute).
For the following:
WITH cte as (
SELECT
DateKey ,
VersionNumber ,
SetID ,
ClassID ,
VariableName ,
PeriodNumber ,
PeriodData
from StagingTable
SELECT
DateKey ,
VersionNumber ,
SetID ,
ClassID ,
VariableName,
[0], [1], [2], [3], ,,,, [360]
into newTable1
from cte
pivot (SUM(PeriodData)
FOR PeriodNumber IN (
[0], [1], [2], [3], ..., [360]
) as pvt;
SELECT *
into newTable2
from PivotTable;
SELECT
DateKey ,
VersionNumber ,
SetID ,
ClassID ,
VariableName ,
PeriodNumber ,
PeriodData
into newTable3
from StagingTable;
The distribution of query cost is strikingly different. The pivot query has a cost of 98% and the other two queries have costs of 1%. The big difference between these queries and the versions that just output the results (in the execution plan)
is in the table insert. The pivot query shows a cost of 26,000 while the select from pivottable shows cost of 160 and select from StagingTable shows cost of 280.
What else can I look at? Also, what else can I try to optimize the pivot query.
For now, I am going to see if I get better performance letting SSRS do the pivoting.
Russel Loski, MCT, MCSE Data Platform/Business Intelligence. Twitter: @sqlmovers; blog: www.sqlmovers.comI have finally nailed down what is causing the bottleneck.
The Compute Scalar step for some reason shows almost no cost to the execution plan. But I noticed that the actual number of rows is 5 million (the same as the scan). It appears that SQL Server expands every row to 360+ columns, all 5 million
of them.
So I did an experiment. I took the table that I was populating and did a cross join to a number table. This table has 30 K rows and 360 columns. I figured that if I select 150 rows from the number table it will generate around 5 million
rows. The results were almost identical to using the MAX(CASE WHEN ...) construct: 1 minute and some change.
I then cross joined with only 75 rows. It took 30 seconds. 37 rows took about 15 seconds.
So the Compute Scalar costs a lot more then the Execution plan analyzer says.
SSIS appears to gather one row at a time. Once it finishes one row, one group by set, it sends the row on its way. So, in my case, the 5 million rows is read in with 7 columns and 30 K rows are output with 365 columns or so.
SQL Server creates 5 million rows with 365 columns, then aggregates them down to 30 K rows.
Thank you, Tom for you discussion with me on this. I think that I can present my thoughts to my lead.
Russel Loski, MCT, MCSE Data Platform/Business Intelligence. Twitter: @sqlmovers; blog: www.sqlmovers.com -
Can't edit and re-Save Power Pivot query with Teradata connection (using LDAP security mechanism) unless "Save my password" option was checked. Without this option I receive this error upon attempt to Save changes made to the query ...
The following exception occurred while the managed IDbConnection interface was being used: [TeraGSS Security Library] [115022] Exception occurred in TERAGSS layer. See inner exception for details.;TdgssAuthenticationTokenExchange delegate threw an exception.
See the inner exception for details.
ErrorCode: -452984642 Severity: Error Facility: DotNet
[Teradata Database] [8017] The UserId, Password or Account is invalid..
A connection could not be made to the data source with the DataSourceID of '6a06124c-496f-4887-bf39-d2582173d499', Name of 'Teradata fsltdprd'.
An error occurred while processing table 'Query'.
The current operation was cancelled because another operation in the transaction failed.Sorry you're right, the Office category isn't currently accepting bug reports in which case Olaf's suggestion to use the smiley face is the way to go. In Excel please go to File > Options > Trust Centre > 'Trust Centre Settings...' and check
that the Feeeback Tool is enabled.
If the option is greyed out like this...
... then you should be able to enable it by changing the value of the 'Enabled' registry key from a 0 to a 1 which you will find under: HKEY_CURRENT_USER\Software\Microsoft\Office\15.0\Common\Feedback. You will then need to close all Office applications
and re-launch Excel 2013.
Once the Feeback Tool has been enabled, you should see the smile face(s) in the top right hand corner of the Excel window and be able to send your feedback.
Regards,
Michael
Please remember to mark a post that answers your question as an answer...If a post doesn't answer your question but you've found it helpful, please remember to vote it as helpful :)
Website: nimblelearn.com, Blog:
nimblelearn.com/blog, Twitter:
@nimblelearn -
Using Power Query to import image files for Power View
I am trying to use Power Query to import image data from a SQL Azure database for use in Power View. I've selected both the source image table and the ?images table in the workbook query. The files seem to load as binary data in the Power
Query editor but when loaded to the data model with Power Pivot, the field becomes "text" type rather than binary. Does anyone know the procedure to use PowerQuery to load image files into PowerPivot?Hi,
We currently do not support loading binary data from Power Query into the Power Pivot data model. This is something we'd like to address soon. For now, you will need to use the Power Pivot import capabilities if you want to achieve this.
Sorry about the inconvenience - we will try to enable this feature over the coming months.
Faisal Mohamood | Program Manager | Data Platform Group - Microsoft -
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 -
APEX 3.2 -ORACLE 10G - PIVOT QUERY
Hello, i searched around the forum and i cound't find an answer to this specific matter, although i saw some replies that were close...
i need to creat a form based on a pivot query. but oracle 10g doesn't support that feature so i hope someone can help me.
my problem is that the number of columns will be variable. here's an example:
ORIGINAL TABLE
NAME KMS VEHICLE
Joe 100 AUDI
Tom 300 VW
Mark 150 FORD
Ann 250 FORD
Joe 200 VW
Tom 123 AUDI
Mark 345 AUDI
Ann 45 VW
Joe 6 FORD
Tom 67 FORD
Mark 46 VW
Ann 99 AUDI
DESIRED RESULT
Joe Tom Mark Ann Vehicle
100 123 345 99 AUDI
6 67 150 250 FORD
200 300 46 45 VW
the new columns will be the values in the old NAME column. BUT these values are variable. today its joe,tom,mark and ann tomorrow it could be silvia, tony,richard,harry , william and jane. this means the usuall replies i saw, using MAX and DECODE will not apply because i never know what values or how many values are in this column. with pivot i can get this done.... how can i do this in oracle 10g? is there a way to creat a ser function Pivot somehow? ideas?
thanks!
Mark Pereira
Edited by: 899716 on Jul 18, 2012 12:02 PMThis is the Oracle Forms forum. Post your question in the SQL forum.
Tip: check the latest Oracle Magazine (July/August 2012). There is an article by Tom Kyte about the same question.
http://www.oracle.com/technetwork/oramag/magazine/home/index.html -
Hi,
I have 2 questions on the pivot query below:
1 - I want to have total by Country and Year
2 - I want to allow the use a dynamic year range (like year between 1990 and 2000)
Thanks,
Ribhi
select * from (
select CNTRY_NAME, MYYEAR,AM_AMOUNT
from yearly_lending t
pivot
sum(AM_AMOUNT)
for MYYEAR in (1974,1975,1976,1977,1978,1979,1980,1981,1982,1983,1984,1985,1986,1987,1988,1989,1990,1991,1992,1993,1994,1995,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009)
order by CNTRY_NAMEHi all,
Thank you for your help.
The qury working as expected, but i wont to add total by country and year
Country 1974 1975 1976 1977 1977 1978...2009 Total
Jordan 10 5 0 3 5 1 24
Egypt 5 0 0 0 10 0 15
Syria 8 2 10 20
Total 23 7 0 3 15 11 59
also would like to select year range rather than entering year by year example year from 2000 to year 2009
I created a view from the qury below and then my pivot query
select
rtrim(cntry.short_name_e) cntry_name,
to_char(e.date0,'yyyy') myYear,
am.value / 1000000 am_amount,
a.fk_countrycode a_cntry
from event e,
agreement_amount am,
agreement a, in_country cntry
where
a.number0 = e.fk_agreementnumber
AND A.SUB_NUMBER <>'P'
AND a.fk_countrycode = cntry.intl_code
and a.sub_number = e.fk_agreementsub_nu
and a.type = e.fk_agreementtype
/*and rtrim(a.status) <> 'CANCELLED' */
and rtrim(e.type) = 'SIGNING'
and rtrim(e.fk_agreementtype) <> 'GRANT'
and e.fk_agreementnumber = am.fk_agreementnumber
and e.fk_agreementsub_nu = am.fk_agreementsub_nu
and e.fk_agreementtype = am.fk_agreementtype
and am.serial_number = 1
order by rtrim(cntry.short_name_e) ,to_char(e.date0,'yyyy')
Best regards,
Ribhi
Edited by: Ribhi on Apr 29, 2009 7:20 PM -
Change the heading sequence of a pivot query
GENERAL LEDGER TOTALS PER GL ACCOUNT PER PERIOD PIVOTED (DATA FROM SQL_GL5203) code to create the Pivot query ******************************************************************************/
DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)
--Get distinct values of the PIVOT Column
SELECT @ColumnName= ISNULL(@ColumnName + ',','')
+ QUOTENAME(Period)
FROM (SELECT DISTINCT PERIOD FROM [dbo].[SQL_GL5203]) AS PERIODS
--Prepare the PIVOT query using the dynamic SET
SET @DynamicPivotQuery =
WITH PivotData AS( SELECT ID, PERIOD,TOTALTRAN
FROM [dbo].[SQL_GL5203])
SELECT id, ' + @ColumnName + '
FROM PivotData
PIVOT( sum(TOTALTRAN)
FOR PERIOD IN ('+ @ColumnName + ')) AS PVTTAB'
--Execute the Dynamic Pivot Query
--DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
EXEC sp_executesql @DynamicPivotQuery
SEE THE ORDER of the query (id, 2015-09 , 2015-06, 2015-03
the periods are not in any order yet
the view it is reading in I in ID AND PERIOD ORDER AND grouped in that order.Running your script I got
Msg 208, Level 16, State 1, Line 4
Invalid object name 'dbo.SQL_GL5203'.
Best Regards,Uri Dimant SQL Server MVP,
http://sqlblog.com/blogs/uri_dimant/
MS SQL optimization: MS SQL Development and Optimization
MS SQL Consulting:
Large scale of database and data cleansing
Remote DBA Services:
Improves MS SQL Database Performance
SQL Server Integration Services:
Business Intelligence
Maybe you are looking for
-
Scanner samsung scx-4300 does not work after software update v 2.3
hi everybody, i just noticed that after i run software update on my mac mini and install samsung printer software update v2.3 I'm no longer able to scan from my Samsung SCX-4300 on macbook pro i noticed the software update has not been installed, and
-
Airport Base Station-Do g devices slow it down? Parental controls
I need to purchase a new Wi-Fi router and am looking at several but am looking at the Airport Base Station. Most of my devices such as my Mac's all use N networking but other devices such as my Xbox 360 use g networking. When doing research on the Ai
-
Yes I am connecting to ITunes and syncing
Yes I am connecting to ITunes and syncing. ITunes shows the amount of data uploaded to the IPod Touch but the Ipod itself says "No Content"
-
Change J2ee parameters on WAS 640-J2EE add in -config tool
I have started the config tool to change java paramters per SAP. However I notice that config tool shows dispatcher and server and below that an instance (xxx-318782 for example) which has a dispatcher and server also..... Why is this and which do I
-
Hi All, I am referring MOS DOCID 553812.1[Actions for the DSTv4 update in the 10.2.0.4 patchset]. I am unable to understand few things from the doc and I have mentioned the portion below. Kindly help me understand the same. +*<Moderator edit - MOS do