SQL Pivot Query
Hi Experts
I recently purchased a copy of Gordon's book to help me create a pivot query based on the examples at the end which I hope to show me a set of data based on my Sales Order tables. Unfortunately I have found it a little too complex.
In my ORDR table I have 10 UDFs which relate to various statuses and dates in the sales order process.
What I would like is to see a pivot table query of the sum quanties of items at the different stages (as rows) against the dates in weeks.
In the rows would be the status UDF fields:
U_DES_STAGE
U_PRN_STAGE
U_PRS_STAGE
U_SEW_STAGE
U_EMB_STAGE
for each UDF there is an associated date UDF
U_DES_STAGE_DATE
U_PRN_STAGE_DATE
U_PRS_STAGE_DATE
U_SEW_STAGE_DATE
U_EMB_STAGE_DATE
The columns I require in the pivot table would be the UDF stage dates which are always input for the week ending Friday.
The data in the pivot should be the sum of the quantities in the sales orders rows RDR1.
Stage
W/E 14/3/2014
W/E 21/3/2014
W/E 28/3/2014
W/E 4/4/2014
W/E 11/4/2014
W/E 18/4/2014
DES
Sum of Qty
Sum of Qty
Sum of Qty
Sum of Qty
Sum of Qty
Sum of Qty
PRN
Sum of Qty
Sum of Qty
Sum of Qty
Sum of Qty
Sum of Qty
Sum of Qty
PRS
Sum of Qty
Sum of Qty
Sum of Qty
Sum of Qty
Sum of Qty
Sum of Qty
SEW
Sum of Qty
Sum of Qty
Sum of Qty
Sum of Qty
Sum of Qty
Sum of Qty
EMB
Sum of Qty
Sum of Qty
Sum of Qty
Sum of Qty
Sum of Qty
Sum of Qty
The problem is that I am not sure as to how to add the WHERE clause to limit the results to only the 5 items (DES% or PRN% or PRS% or SEW% or EMB%)
I would be very grateful for any assistance.
Regards
Geoff
Hi Gordon - you're very welcome. The content of the book is very helpful to an SQL novice!
Essentially the 10 UDF are for recording each stage of the processes involved in the sales order. there are 5 processes so each process has 2 fields - one records the initals of the staff member who is responsible and the other records the date the process is scheduled for.
We want to be able to produce a schedule to show us how many garments are scheduled on a sales order in a particular week effectively turning this table into the one below it:
Document Number
Quantity
Design - Scheduled Date
Dye Print Scheduled Date
Dye Press Scheduled Date
Dye Sewing Scheduled Date
Embroidery - Scheduled Date
Print – Scheduled Date
298835
315
12.07.10
06.09.10
300058
144
22.07.10
06.09.10
300921
29
01.10.10
302330
15
30.09.10
30.09.10
302820
460
05.10.10
302833
55
20.09.10
22.09.10
303476
86
06.10.10
06.10.10
303948
13
11.08.10
11.08.10
303982
106
26.10.10
27.10.10
304012
99
25.11.10
25.11.10
304186
6
27.08.10
27.08.10
304331
10
07.09.10
07.09.10
304382
16
29.09.10
29.09.10
304399
15
19.08.10
304556
85
01.10.10
22.10.10
304557
11
29.09.10
29.09.10
304563
8
29.09.10
29.09.10
304567
7
29.09.10
304570
19
01.10.10
22.10.10
304571
113
01.10.10
22.10.10
304576
11
29.09.10
29.09.10
304603
72
22.09.10
23.09.10
304604
86
22.09.10
23.09.10
304606
107
22.09.10
23.09.10
304608
107
22.09.10
23.09.10
304613
107
22.09.10
23.09.10
304693
12
29.09.10
29.09.10
304710
5
29.09.10
304760
6
29.09.10
29.09.10
304765
4
29.09.10
304899
42
15.09.10
304963
100
22.09.10
24.09.10
304974
719
27.09.10
29.09.10
304975
401
28.09.10
29.09.10
Similar Messages
-
HUM ADG DYS (NIA, SIM, TRC, TRX) SMALL BRANDS (LUP, KAL,CRN,LPP,SYN)
MON TUE WED THURS FRI MON TUE WED THURS FRI MON TUE WED THURS FRI MON TUE WED THURS FRI
VENDOR
INT
QUAN
STER
LASH
OSP
HIB
PROD
I’d like to put together a query to populate the tables above,like count of recods for each vendor for each brand with the criteria for selecting within one week.
Here vendor_cd(INT,QUAN,STER,...etc),brand_cd(HUM,ADG,NIA,SIM,..eyc).we are extracting the details from file detail table whose column are like FILE_ID,FILE_RECEIPT_TS,REC_INSERT_TS,VENDOR_CD,BRAND_CD,RECORD_COUNT.
Edited by: ASHWINI89 on Mar 21, 2013 8:33 PMWelcome to the forum!!
Please consider the following when you post a question. This would help us help you better
1. New features keep coming in every oracle version so please provide Your Oracle DB Version to get the best possible answer.
You can use the following query and do a copy past of the output.
select * from v$version 2. This forum has a very good Search Feature. Please use that before posting your question. Because for most of the questions
that are asked the answer is already there.
3. We dont know your DB structure or How your Data is. So you need to let us know. The best way would be to give some sample data like this.
I have the following table called sales
with sales
as
select 1 sales_id, 1 prod_id, 1001 inv_num, 120 qty from dual
union all
select 2 sales_id, 1 prod_id, 1002 inv_num, 25 qty from dual
select *
from sales 4. Rather than telling what you want in words its more easier when you give your expected output.
For example in the above sales table, I want to know the total quantity and number of invoice for each product.
The output should look like this
Prod_id sum_qty count_inv
1 145 2 5. When ever you get an error message post the entire error message. With the Error Number, The message and the Line number.
6. Next thing is a very important thing to remember. Please post only well formatted code. Unformatted code is very hard to read.
Your code format gets lost when you post it in the Oracle Forum. So in order to preserve it you need to
use the {noformat}{noformat} tags.
The usage of the tag is like this.
<place your code here>\
7. If you are posting a *Performance Related Question*. Please read
{thread:id=501834} and {thread:id=863295}.
Following those guide will be very helpful.
8. Please keep in mind that this is a public forum. Here No question is URGENT.
So use of words like *URGENT* or *ASAP* (As Soon As Possible) are considered to be rude. -
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 -
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 -
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.0My 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. -
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 -
11G Pivot Query with parameters
Hello all,
I would like to find some way, any way to pass parameters to a pivot query. The following pivot query works, but I would like segment2 to be a variable as well as the period names so....
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 >='007611' and segment2 <='007751' AND period_name in ('SEP-08','OCT-08','NOV-08'))
pivot
sum(accounted_dr)
for period_name in ('SEP-08','OCT-08','NOV-08') )
....would be something like....
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_OBJECT_FROM AND and segment2 <=:P4_OBJECT_TO AND period_name in &P4_EPSB_PERIOD_HOLD.)
pivot
sum(accounted_dr)
for period_name in (&P4_EPSB_PERIOD_HOLD.) )
It is our understanding that we have to hardcode period names and objects, but we would like to get around that. Does anyone have any ideas or tricks?
Thankslilhelp 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. -
Having a problem with writing pivoting query.
Hi All,
I have a query with one input parameter. It gives different result based on the input provided.
For example
1. If i give input as date1 the output would be as follows.
Col1 Col2 Col3
name1 v1 10
name1 v2 14
name2 v1 15
name3 v3 202. If i give input as date2 the output would be as follows.
Col1 Col2 Col3
name2 v1 14
name2 v2 10
name3 v1 8
name3 v2 14
name1 v1 10
name1 v2 34
name1 v4 23
name1 v5 10
name4 v1 12
name4 v2 14
name4 v4 18
name4 v5 20
name5 v1 14
name5 v2 10and so on for diff inputs, I get diff output.
Now, I am trying to write a query which would give me the pivot data on the outputs shown above.
For Example
1. For the first output on the top, the pivot query should return the data as follows:
name1 name2 name3
v1 10 15 0
v2 14 0 0
v3 0 0 202. For the second output on the top, the pivot query should return the data as follows:
name1 name2 name3 name4 name5
v1 10 14 8 12 14
v2 34 10 14 14 10
v3 0 0 0 0 0
v4 23 0 0 18 0
v5 10 0 0 20 0and so on...
I would be greatly thankful for any kind of input provided since.
Regards
SapanHi Frank,
Thanks for your response, I did have a look at the thread which had the options for both static as well as the dynamic pivoting.
But as you said this scenario needs a dynamic SQL. The only constraint is, I need to plug in the SQL into HTML-DB and spooling would not be feasible. That's the reason I am trying to frame a query around the current query which gives me the base data to be pivoted. I am also keeping my options open on coming up with PL/SQL block, which can integrate well with HTML-DB.
Any thoughts/suggestions would be helpful.
Thank you. -
Oracle SQL Select query takes long time than expected.
Hi,
I am facing a problem in SQL select query statement. There is a long time taken in select query from the Database.
The query is as follows.
select /*+rule */ f1.id,f1.fdn,p1.attr_name,p1.attr_value from fdnmappingtable f1,parametertable p1 where p1.id = f1.id and ((f1.object_type ='ne_sub_type.780' )) and ( (f1.id in(select id from fdnmappingtable where fdn like '0=#1#/14=#S0058-3#/17=#S0058-3#/18=#1#/780=#5#%')))order by f1.id asc
This query is taking more than 4 seconds to get the results in a system where the DB is running for more than 1 month.
The same query is taking very few milliseconds (50-100ms) in a system where the DB is freshly installed and the data in the tables are same in both the systems.
Kindly advice what is going wrong??
Regards,
PurushothamSQL> @/alcatel/omc1/data/query.sql
2 ;
9 rows selected.
Execution Plan
Plan hash value: 3745571015
| Id | Operation | Name |
| 0 | SELECT STATEMENT | |
| 1 | SORT ORDER BY | |
| 2 | NESTED LOOPS | |
| 3 | NESTED LOOPS | |
| 4 | TABLE ACCESS FULL | PARAMETERTABLE |
|* 5 | TABLE ACCESS BY INDEX ROWID| FDNMAPPINGTABLE |
|* 6 | INDEX UNIQUE SCAN | PRIMARY_KY_FDNMAPPINGTABLE |
|* 7 | TABLE ACCESS BY INDEX ROWID | FDNMAPPINGTABLE |
|* 8 | INDEX UNIQUE SCAN | PRIMARY_KY_FDNMAPPINGTABLE |
Predicate Information (identified by operation id):
5 - filter("F1"."OBJECT_TYPE"='ne_sub_type.780')
6 - access("P1"."ID"="F1"."ID")
7 - filter("FDN" LIKE '0=#1#/14=#S0058-3#/17=#S0058-3#/18=#1#/780=#5#
8 - access("F1"."ID"="ID")
Note
- rule based optimizer used (consider using cbo)
Statistics
0 recursive calls
0 db block gets
0 consistent gets
0 physical reads
0 redo size
0 bytes sent via SQL*Net to client
0 bytes received via SQL*Net from client
0 SQL*Net roundtrips to/from client
0 sorts (memory)
0 sorts (disk)
9 rows processed
SQL> -
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 ;) -
hi friends,
i've a view called "risk_efforts" with fields user_id,user_name,wknd_dt,week_day,prod_efforts,unprod_efforts.
Name Type
ROW_ID NUMBER
USER_ID VARCHAR2(14)
USER_NAME VARCHAR2(50)
WKND_DT VARCHAR2(8)
WEEK_DAY VARCHAR2(250)
PROD_EFFORTS NUMBER
UNPROD_EFFORTS NUMBER
data is like this:
when there is some data in prod_efforts, unprod_efforts will be null
when there is some data in unprod_efforts, prod_efforts will be null
for example:
USER_ID USER_NAME WKND_DT WEEK_DAY PROD_EFFORTS UNPROD_EFFORTS
G666999 GTest 20100403 TUE null 3
G666999 GTest 20100403 TUE 14 null
now i want to combine these 2 rows into 1 row i.e o/p should be like this
USER_ID USER_NAME WKND_DT WEEK_DAY PROD_EFFORTS UNPROD_EFFORTS
G666999 GTest 20100403 TUE 14 3
i've tried all combinations but couldn't get the query. Please help me with the exact SQL select query.
thanks,
GirishWelcome to the forum.
First read this:
Urgency in online postings
Secondly, it's always helpful to provide the following:
1. Oracle version (SELECT * FROM V$VERSION)
2. Sample data in the form of CREATE / INSERT statements.
3. Expected output
4. Explanation of expected output (A.K.A. "business logic")
5. Use \ tags for #2 and #3. See FAQ (Link on top right side) for details.
You have provided #3 and #4. However with no usable form of sample data forum members will often not respond as quickly as they could if you provided #2.
I'm just wagering a guess here but what about this:SELECT ROW_ID
, USER_ID
, WKND_DT
, WEEK_DAY
, MAX(PROD_EFFORTS) AS PROD_EFFORTS
, MAX(UNPROD_EFFORTS) AS UNPROD_EFFORTS
FROM RISK_EFFORTS
GROUP BY ROW_ID
, USER_ID
, WKND_DT
, WEEK_DAY -
Can we use multiple "pivot_for_clauses" in 11g SQL PIVOT
Can we use multiple "pivot_for_clauses" in 11g SQL PIVOT. Below SQL is an example of what I am trying to do - In this case instead of using JOIN, can I have three pivot_for_clauses in the same sql?
SQL:
MERGE INTO Test_1 dest
USING (SELECT P1.company_id,trunc(sysdate) as load_date,num_logins,......
FROM (SELECT company_id,action_type_id
FROM Testauditinfo_1 where trunc(audit_date_time)=trunc(sysdate)-1) a
PIVOT (count(action_type_id) FOR (action_type_id) IN ((1) as num_logins,(2) as num_logouts,(61) as
num_logins_from_mobile_device,(16) as num_pref_changed,....)) P1
JOIN
(SELECT company_id,action_type_id,tx_type_id
FROM Testauditinfo_1 where trunc(audit_date_time)=trunc(sysdate)-1) a
PIVOT (count(action_type_id) FOR (action_type_id,tx_type_id) IN ((3,4) AS add_invoice, (4,4) AS
edit_invoice,(3,3) as num_checks,(3,47) as num_paychecks,(3,7) as num_recvd_payments,(3,9) as num_bills,
(3,35) as num_estimates,(3,46) as num_purchase_orders)) P2
on P1.company_id=P2.company_id
JOIN
(SELECT company_id,action_type_id,list_type_id
FROM Testauditinfo_1 where trunc(audit_date_time)=trunc(sysdate)-1) a
PIVOT (count(action_type_id) FOR (action_type_id,list_type_id) IN ((3,2) AS num_items,(3,1) as
num_accounts,(3,4) as num_employees,(3,6) as num_customers,(3,14) as num_memorized_reports)) P3
on P2.company_id=P3.company_id
left outer JOIN
(SELECT company_id,create_date,count(*) as num_logos
FROM qbo.companylogos_1 group by company_id,create_date having trunc(create_date)=trunc(sysdate)-1) P4
on P3.company_id=P4.company_id
ORDER BY P1.company_id) source
ON ((dest.company_id = source.company_id) and (dest.load_date = source.load_date))WHEN MATCHED THEN
UPDATE SET dest.num_items = source.num_items where 1=2
WHEN NOT MATCHED THEN
INSERT (dest.company_id,.....) values (source.company_id,.....);Maybe
MERGE INTO Test_1 dest
USING (SELECT P1.company_id,trunc(sysdate) as load_date,num_logins,......
FROM (select *
from (SELECT company_id,action_type_id
FROM Testauditinfo_1
where trunc(audit_date_time) = trunc(sysdate)-1
) a
PIVOT (count(action_type_id)
FOR (action_type_id) IN ((1) as num_logins,
(2) as num_logouts,(61) as num_logins_from_mobile_device,
(16) as num_pref_changed,....
) P1
JOIN
(select *
from (SELECT company_id,action_type_id,tx_type_id
FROM Testauditinfo_1
where trunc(audit_date_time) = trunc(sysdate)-1
) a
PIVOT (count(action_type_id)
FOR (action_type_id,tx_type_id) IN ((3,4) AS add_invoice,
(4,4) AS edit_invoice,
(3,3) as num_checks,
(3,47) as num_paychecks,
(3,7) as num_recvd_payments,
(3,9) as num_bills,
(3,35) as num_estimates,(3,46) as num_purchase_orders
) P2
on P1.company_id = P2.company_id
JOIN
(select *
from (SELECT company_id,action_type_id,list_type_id
FROM Testauditinfo_1
where trunc(audit_date_time) = trunc(sysdate)-1
) a
PIVOT (count(action_type_id)
FOR (action_type_id,list_type_id) IN ((3,2) AS num_items,
(3,1) as num_accounts,
(3,4) as num_employees,
(3,6) as num_customers,
(3,14) as num_memorized_reports
) P3
on P2.company_id = P3.company_id
left outer JOIN
(SELECT company_id,create_date,count(*) as num_logos
FROM qbo.companylogos_1
group by company_id,create_date
having trunc(create_date) = trunc(sysdate)-1
) P4
on P3.company_id = P4.company_id
ORDER BY P1.company_id
) source
ON ((dest.company_id = source.company_id) and (dest.load_date = source.load_date))
WHEN MATCHED
THEN UPDATE SET dest.num_items = source.num_items where 1 = 2
WHEN NOT MATCHED
THEN INSERT (dest.company_id,.....)
values (source.company_id,.....)Did you try it ?
Regards
Etbin
Maybe you are looking for
-
HT204384 maximum size for sdxc?
I like to buy a new macbook pro retina with 256MB SSD. I would expand it with a sdxc card, but what is the maximum size of such a card? For now I think 64GB, but is there really no 128GB or more available? Thanks for your reaction Kurt
-
Duplicate Invoice Reference Number
Dear All I have a requirement that while Parking an Invoice system should tell me for Duplicate Invoice Number exists, when I am enetring it in Reference filed MIR7. Regards Manoj
-
Resource related billing project system
Hi guru, I have the following questions: 1) It is possible to use RRB in PS without use the easy cost planning? IF yes, which is the transaction? 2) For use RRB, I have to created first a sales document linked to WBE or the system create sales order
-
Running Extension Points sample Helloworld gives Error: unable to load...
Hi.... It looks like I don't have cez_inproc in my library path? I am just wondering is there anything I am missing? I followed all the directions correctly as mentioned in the webi extension doc. Thanks, -gandhams java.lang.UnsatisfiedLinkError: n
-
Drums tracks won't show in tracks window
Hey mates, Just started to work with NI Modern-Drums. I wanted to be able to edit every single drum, so I've opened it in "multi-out" option... My question is: I can see only the kick track in the main window. How can I make the other 15 tracks show