Pivot query problem
All (running 11.2 on OEL 5),
I am struggling figuring out how to get the result I want with the following data:
CREATE TABLE REGION_LOOKUP
( REGION_ID NUMBER NOT NULL ENABLE,
REGION VARCHAR2(5) NOT NULL ENABLE,
PRIMARY KEY ("REGION_ID") ENABLE
CREATE TABLE IND_REVENUE
( ID NUMBER,
IND_REV_DATE VARCHAR2(30),
IND_REVENUE NUMBER,
REGION_ID NUMBER,
CONSTRAINT IND_REVENUE_PK PRIMARY KEY (ID) ENABLE
INSERT INTO REGION_LOOKUP (REGION_ID, REGION VALUES(1,'EMEA');
INSERT INTO REGION_LOOKUP (REGION_ID, REGION VALUES(2,'LAD');
INSERT INTO REGION_LOOKUP (REGION_ID, REGION VALUES(3,'APAC');
INSERT INTO REGION_LOOKUP (REGION_ID, REGION VALUES(4,'NAS');
INSERT INTO REGION_LOOKUP (REGION_ID, REGION VALUES(5,'JAPAN');
INSERT INTO IND_REVENUE VALUES(1,'10-Jun',73.10,4);
INSERT INTO IND_REVENUE VALUES(2,'10-Jul',49.30,4);
INSERT INTO IND_REVENUE VALUES(3,'10-Jun',3.20,2);
INSERT INTO IND_REVENUE VALUES(4,'10-Jul',0.30,2);
INSERT INTO IND_REVENUE VALUES(5,'10-Jun',28.60,3);
INSERT INTO IND_REVENUE VALUES(6,'10-Jul',12.40,3);
INSERT INTO IND_REVENUE VALUES(7,'10-Jun',64.00,1);
INSERT INTO IND_REVENUE VALUES(8,'10-Jul',19.80,1);
INSERT INTO IND_REVENUE VALUES(9,'10-Jun',6.60,5);
INSERT INTO IND_REVENUE VALUES(10,'10-Jul',4.70,5);
/The result I'd like to get is as follows. The date column 10-Jun and 10-Jul is "dynamic" as there will be a new column every month.
Region 10-Jun 10-Jul Total
APAC $28.6 $12.4 $41.0
EMEA $64.0 $19.8 $83.8
JAPAN $6.6 $4.7 $11.3
LAD $3.2 $0.3 $3.5
NAS $73.1 $49.3 $122.4
Total $175.5 $86.5 $262.0I am thinking something like this (I am stuck) but this obviously doesn't work at all and is also hard coded with regards to the columns.
select rn, 10-Jun, 10-Jul, (10-Jun + 10-Jul) as Total from
(select RL.REGION_NAME as rn, RL.REGION as re, IR.IND_REVENUE as rev
from REGION_LOOKUP RL,
IND_REVENUE IR where IR.region_id = RN.region_id)
pivot (SUM(rev) for rn in
('10-Jun' as 10-Jun,
'10-Jul' as 10-Jul))Any great ideas?
Cheers,
Andy
Fixed the insert statements, sorry about that. Copy and paste before coffee isn't good.
Hi, Andy,
A Tael wrote:
A nice solution, Thanks, but which solution do you mean? There were at least 4 different soltuions on that page.
but isn't there a way to avoid the spooling into a file?Do you mean the dynamic SQL solution? Yes, SPOOLing is just one way to do dynamic SQL.
In SQL*Plus you can write the variable part of the query to a substitution variable (see below).
In PL/SQL, you can assemble a SELECT statement in VARCHAR2 variables.
PROMPT ========== 2. Dynamic Pivot using Substitution Variable ==========
-- ***** Preliminary Query: *****
COLUMN sql_txt_col NEW_VALUE sql_txt
WITH all_jobs AS
SELECT DISTINCT
job
, DENSE_RANK () OVER (ORDER BY job) AS r_num
FROM scott.emp
SELECT SYS_CONNECT_BY_PATH ( job || ''' THEN 1 END) AS '
|| job
|| '_CNT'
|| CHR (10) -- Newline, for legibility only
, ', COUNT (CASE WHEN job = ''' -- Delimiter, goes before each entry
) AS sql_txt_col
FROM all_jobs
WHERE CONNECT_BY_ISLEAF = 1
START WITH r_num = 1
CONNECT BY r_num = PRIOR r_num + 1
-- ***** Main Query *****
SELECT deptno
&sql_txt -- Ends with newline, so occupy that line
FROM scott.emp
GROUP BY deptno
ORDER BY deptno
EXPLANATION:
Using a substitution variable is very similar to using a script.
The main difference is that the output of the preliminary query has to
go into one row. This is done with SYS_CONNECT_BY_PATH, and getting
that requires that the jobs be numbered with consecutive integers, 1, 2, 3, ...
which we get from DENSE_RANK.
The NEWLINE character was added just to make the output line easier
to read during debugging.
*/
Similar Messages
-
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. -
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 -
Pivot query, phantom behavior, possible bug?
Hi experts,
Oracle 11g
We are trying to construct a binary type table using a pivot query. (I know there will be no 0's, I will fill that in later.)
The query to create this table is as follows:
create table TEMP_T1 as
select * from (
select master_id, mbr_id
sub_id,
NVL(max(den_flag),0) DF,
NVL(max(num_flag),0) NF,
NVL(sum(den_flag),0) DXF,
NVL(sum(num_flag),0) NXF
from MEM_SUM
group by master_id, mbr_id,
sub_id
pivot ( max(DF) D_FLAG,
max(NF) N_FLAG,
sum(DXF) D_COUNT,
sum(NXF) N_COUNT
FOR sub_id in
( 'MEAS-1' AS "MEAS1",'MEAS-2' AS "MEAS2",'MEAS-3' AS "MEAS3",'MEAS-4' AS "MEAS4"))I am seeing unusual results when I run this query, and am unsure why. Wanted to get some thoughts.
First issue:
Although the query selects master_id and mbr_id, I only get master_id with the pivoted results (when it should be master_id, mbr_id & pivot results). Not sure why.
Second issue:
And this is where it gets even more strange, if I
1) do something to the code to make it have a syntax problem, re-run, it will fail, naturally.
then
2) fix the syntax back to the original query above, it will run and return master_id, mbr_id & the pivoted results.
Has anyone encountered such a strange issue before? Any suggestions on a solution welcome.
Edited by: chris001 on Feb 22, 2013 8:09 AMI've experienced a similar problem with my FaderPort controller but only under odd circumstances.
If I accidentally unplugged my FaderPort and then plugged it back in, the Control Surfaces preferences that I had assigned it would get deleted and the MIDI messages would come through as note data and other really weird stuff depending on what track I had selected in the arrange window...
What I noticed was that when I just went in and re-did my Control Surfaces stuff for that controller it would reset and work perfectly.
Eventually I had to contact PreSonus and let them know what was happening. Turns out it was a problem with the driver, and the driver had to be updated to accomodate 8.0.2.
I can only imagine that this is still the case for many companies (including the ones who made your volume pedal) since Logic 9 came so suddenly, without even a 8.1 ever being released....Try contacting that company and seeing if there are any known issues with the driver for the device and Logic 9... might help, can't hurt. -
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
GeoffHi 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 -
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 ;) -
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 -
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 -
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. -
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 -
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.
Maybe you are looking for
-
When I sign into my email account I am brought to the "Email Preview" page. When I click on "email", "address book" or any of the other files, it tries to connect. In the box at the top it says "connect, then Zimbra, then connect again. Then I am bro
-
I have a new LG 3D LCD TV and a Toshiba laptop. I want to connect my laptop to TV so I can watch Netflix, I've got the 15 pin connector and have video displayed on the TV no problem. I don't know how to get the audio off the laptop and onto the TV
-
hi, i want to make a "staff training loan" account a recon account. but there is a balance in that account. therefore system is not letting me to make this account a recon account. can't I transfer the balance to different account??and them make "sta
-
InDesign CS6 Extension and JSON
Hi everybody I'm just building up an InDesign CS6 Extension and would like to use JSON. JSON should be native with Flash-Players > version 11 but if I set the Flex Compiler -> Flash Player Options to version 11.0.0 the JSON-commands still won't be re
-
ITunes store in German after v7.0 upgrade?
Just upgraded to v7.0 and my iTunes store headers are displayed in German. Selected language in iTunes preferences is English. How do I change the iTunes store language? Thanks Phil