Dynamic display of columns in pivot query
I have a table called STUDENT_SCORE . I need to display the avarage score /month for past 2 years and the monthly score till today' month.
So suppose this is April 2009. The report will look like
Roll_id 2007avg 2008avg Jan09 Feb 09 Mar09
101 80.9 70.9 89.7 56.8 90.9
102 70.9 23.9 87.2 90.0 76.8
I have tried a bit , but can not fix the display of monthly score dynamically.
the DDL/DML is as below
create table STUDENT_SCORE
(roll_id number,
mth_id date,
score number) ;
insert into STUDENT_SCORE values
(101, to_date('01/01/2006', 'mm/dd/yyyy') , 67.5);
insert into STUDENT_SCORE values
(101, to_date('02/01/2006', 'mm/dd/yyyy') , 77.5);
insert into STUDENT_SCORE values
(101, to_date('03/01/2006', 'mm/dd/yyyy') , 87.5);
insert into STUDENT_SCORE values
(101, to_date('04/01/2006', 'mm/dd/yyyy') , 27.5);
insert into STUDENT_SCORE values
(101, to_date('05/01/2006', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(101, to_date('06/01/2006', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(101, to_date('07/01/2006', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(101, to_date('08/01/2006', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(101, to_date('09/01/2006', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(101, to_date('10/01/2006', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(101, to_date('11/01/2006', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(101, to_date('12/01/2006', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(101, to_date('01/01/2007', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(101, to_date('02/01/2007', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(101, to_date('03/01/2007', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(101, to_date('04/01/2007', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(101, to_date('05/01/2007', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(101, to_date('06/01/2007', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(101, to_date('07/01/2007', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(101, to_date('08/01/2007', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(101, to_date('09/01/2007', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(101, to_date('10/01/2007', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(101, to_date('11/01/2007', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(101, to_date('12/01/2007', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(101, to_date('01/01/2008', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(101, to_date('02/01/2008', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(101, to_date('03/01/2008', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(101, to_date('04/01/2008', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(101, to_date('05/01/2008', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(101, to_date('06/01/2008', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(101, to_date('07/01/2008', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(101, to_date('08/01/2008', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(101, to_date('09/01/2008', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(101, to_date('10/01/2008', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(101, to_date('11/01/2008', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(101, to_date('12/01/2008', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(101, to_date('01/01/2009', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(102, to_date('01/01/2006', 'mm/dd/yyyy') , 67.5);
insert into STUDENT_SCORE values
(102, to_date('02/01/2006', 'mm/dd/yyyy') , 77.5);
insert into STUDENT_SCORE values
(102, to_date('03/01/2006', 'mm/dd/yyyy') , 87.5);
insert into STUDENT_SCORE values
(102, to_date('04/01/2006', 'mm/dd/yyyy') , 27.5);
insert into STUDENT_SCORE values
(102, to_date('05/01/2006', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(102, to_date('06/01/2006', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(102, to_date('07/01/2006', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(102, to_date('08/01/2006', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(102, to_date('09/01/2006', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(102, to_date('10/01/2006', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(102, to_date('11/01/2006', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(102, to_date('12/01/2006', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(102, to_date('01/01/2007', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(102, to_date('02/01/2007', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(102, to_date('03/01/2007', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(102, to_date('04/01/2007', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(102, to_date('05/01/2007', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(102, to_date('06/01/2007', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(102, to_date('07/01/2007', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(102, to_date('08/01/2007', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(102, to_date('09/01/2007', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(102, to_date('10/01/2007', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(102, to_date('11/01/2007', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(102, to_date('12/01/2007', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(102, to_date('01/01/2008', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(102, to_date('02/01/2008', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(102, to_date('03/01/2008', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(102, to_date('04/01/2008', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(102, to_date('05/01/2008', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(102, to_date('06/01/2008', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(102, to_date('07/01/2008', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(102, to_date('08/01/2008', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(102, to_date('09/01/2008', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(102, to_date('10/01/2008', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(102, to_date('11/01/2008', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(102, to_date('12/01/2008', 'mm/dd/yyyy') ,57.5);
insert into STUDENT_SCORE values
(102, to_date('01/01/2009', 'mm/dd/yyyy') ,57.5);
Hi,
Run this script:
-- Suppress SQL*Plus features that interfere with raw output
SET FEEDBACK OFF
SET LINESIZE 200
SET PAGESIZE 0
-- The prelimiary query produces two rows like this, for the last two complete years
-- , AVG (CASE WHEN TO_CHAR (mth_id, 'YYYY') = '2008' THEN score END) AS "2008avg"
-- It also produces 0 to 11 rows like the following, for every complete month in the current year
-- , AVG (CASE WHEN TO_CHAR (mth_id, 'YYYYMM') = '200901' THEN score END) AS "Jan09"
SPOOL dynamic_part.sql
-- Preliminary query, to create dynamic_part.sql
SELECT ', AVG (CASE WHEN TO_CHAR (mth_id, ''YYYY'
|| CASE -- Add 'MM' except for 1st two rows
WHEN LEVEL > 2
THEN 'MM'
END
|| ''') = '''
|| CASE -- YYYY or YYYYMM
WHEN LEVEL <= 2
THEN TO_CHAR ( ADD_MONTHS ( &target_month
, 12 * (-3 + LEVEL)
, 'YYYY'
ELSE TO_CHAR ( ADD_MONTHS ( TRUNC (&target_month, 'YYYY')
, LEVEL - 3
, 'YYYYMM'
END
|| ''' THEN score END) AS "'
|| CASE -- '2008avg' or 'Jan09'
WHEN LEVEL <= 2
THEN TO_CHAR ( ADD_MONTHS ( &target_month
, 12 * (-3 + LEVEL)
, 'YYYY"avg'
ELSE TO_CHAR ( ADD_MONTHS ( TRUNC (&target_month, 'YYYY')
, LEVEL - 3
, 'MonYY'
END
|| '"'
FROM dual
CONNECT BY LEVEL <= 2 + MONTHS_BETWEEN (&target_month, TRUNC (&target_month, 'YYYY'))
SPOOL OFF
-- Restore SQL*Plus features suppressed earlier
SET FEEDBACK ON
SET LINESIZE 80
SET PAGESIZE 50
-- Main query
SELECT roll_id
@dynamic_part.sql
FROM student_score
GROUP BY roll_id
ORDER BY roll_id;
{code}
I defined the substitution variable target_month like this:
{code}
DEFINE target_month = "TO_DATE ('April 2009', 'Month YYYY')"
{code}
You can use SYSDATE wherever I used &target_month.
With the sample data you posted, I got this output:
{code}
. ROLL_ID 2007avg 2008avg Jan09 Feb09 Mar09
101 57.5 57.5 57.5
102 57.5 57.5 57.5
{code}
Similar Messages
-
Dynamically display/hide columns according to user inputs
Hi,
I need to display or hide columns in reports based on user input. ie. I have several prompts, if user doesn't input values, then the associated columns will not be displayed in the report. Is there a way to achieve this in BO XI R2. Greatly appreciated for your help.Hi Andy,
You can't hide them totally, but you can get close using alerters.
Build an alerter (probably a formula one) that put the value ="" in the field.
Now the formula should test the userresponse for that column,
based on the contents of it (filled in --> false, otherwise --> true).
Apply the alerter to all cells of the column. It will empty completely when the prompt was not filled.
Just set the width of the column to automatic (best use the header cell only) and the minimum width on zero. It will shrink the width when empty, making it seem as if hidden.
Good luck,
Marianne -
Dynamic selection of columns in report and print the output
Hi,
I tried to have dynamic selection of columns in SQL query using lexical parameter. The hitch is how to print those selected column in excel ouput ?
Suppose
I have select &col from table_name
Initial value of &col is col1 and in data layout only col1 appears
where &col was replaced with more than a column (col1,col2,col3)
now how to print the column selected at the run time,
i have coded in Before Report Trigger
:cell_val := ' <td><rw:field id:"cl1" src="col1"></rw:field></td>
<td><rw:field id:"cl2" src="col2"></rw:field></td>
<td><rw:field id:"cl3" src="col3"></rw:field></td> ' ;
and this user parameter was replaced in web source using JSP expression
<rw:getvalue id: "v_cell" src:"cell_val"></rw:getvalue>
<rw:foreach src:"g_val">
<table>
<tr>
<% =v_cell%>
</tr>
</table>
</rw:foreach>
but in the output i can see only blank columns
Regards
SureshThe strings replaced by expression <%= v_cell %>
should print the field values contained in col1,col2,col3 columns, but nothing is printed . i think the custom tags (rw...) are not replaced by the jsp expression properly. -
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 -
Displaying dynamic columns in the query output.
Hello,
Depending on current quarter output of the query would vary.
If current quarter is 'Q1'
O/p : InvQ1 Del BackQ1 BackQ2 BackQ3 BackQ4
If current quarter is 'Q2'
O/p : InvQ1 InvQ2 Del BackQ2 BackQ3 BackQ4
If current quarter is 'Q3'
O/p : InvQ1 InvQ2 InvQ3 Del BackQ3 BackQ4
If current quarter is 'Q4'
O/p : InvQ1 InvQ2 InvQ3 InvQ4 Del BackQ4
So, out of 9 columns, 6 columns would display at any given time depending on the current quarter.
Invoice of 4 quarters, Deliquency and Backlog of 4 quarters.
I am not getting any way how to display dynamic columns or hide unwanted/blank columns.
For the time being I have added all 9 columns in the query, and in the output unwanted columns shows blank.
Can anybody please suggest me how to display only 6 columns in the output depending on current quarter.
Thanks and Regards
ShilpaHello,
This shouldn't be too difficult. Assuming you have a variable with the selected quarter, you may choose to display Inv (whatever that is) for quarters 1 through variable, Del, and Back for quarters variable through 4. You also need a drilldown on quarter in the columns (after the key figure structure). You would probably need to restrict 'Del' on the variable as well if you haven't already done it.
Best regards,
Christoffer -
How can I display multiple column results of a sql query?
I'm wanting to display the results of a query selecting from multiple columns, but I can't seem to find an item type that will allow this. I've tried LOV, multiselect, display as text and others. Any ideas on how to do this. Here is my basic query:
Select ul.meaning,
rqa.submission_date,
rqa.location_num
from
cfa_rqa_doc_submit_dates rqa,
cfa_user_lookups ul
where
rqa.location_num in (Select location_num from cfa_current_locations_mv
where operator_person_id = :P1_PERSON_ID and substr(location_num,1,1) = '8')
and
ul.lookup_type_id='1269'
and
to_char(rqa.submission_date, 'month') = to_char(sysdate, 'month')
and
rqa.submission_date >= (SYSDATE-365)
and ul.lookup_ID= rqa.document_type_id
;Hi,
Do you just wish to display the result of the query? If so, you can simply parse it out in HTML.
You can then choose if you want to use tables or css.
Multiple column layout in tables are based on <tr> and <td>.
<tr> is a table row, where <td> is a column.
All tags should be closed.
Example:
<table>
<tr>
<td>col1</td><td>col2</td>
</tr>
<tr>
<td colspan="2">spans over 2 cols</td>
</tr>
</table>If you want to do the same in css:
(Seems this forum removes the styles!):
float:left; width:50; << first div and 2 div (col 1 and col 2 style)
float:left;clear:both; width:100%; << clear both, double width (spans over 2)
<div>
<div style="float:left; width:50;">col1</div><div style="float:left;width:50%;">col2</div>
<div style="float:left;clear:both; width=100%;">Spans over 2 cols</div>
</div>The div might look more complicated, but if you refrain from styling in the tags them selves, you can define different styles in the .css file.
You need the clear:both to start a new line with the divs that float.
I usually run a dedicated "new line" div, without content.. (exception beeing the html-entities version of ' ' (& nbsp ; << without the spaces)).
eg.:
<div style="cls"> </div>Parsing out the values from the PL SQL you do like so:
begin
declare
cursor c_search is
Select ul.meaning,
rqa.submission_date,
rqa.location_num
from
cfa_rqa_doc_submit_dates rqa,
cfa_user_lookups ul
where
rqa.location_num in (Select location_num from cfa_current_locations_mv
where operator_person_id = :P1_PERSON_ID and substr(location_num,1,1) = '8')
and
ul.lookup_type_id='1269'
and
to_char(rqa.submission_date, 'month') = to_char(sysdate, 'month')
and
rqa.submission_date >= (SYSDATE-365)
and ul.lookup_ID= rqa.document_type_id
begin
htp.p('<div style="width:80%;">');
for v_search in c_search loop
htp.p('<div style="float:left;clear:none;">'||v_search.location_num||'</div>');
htp.p('<div style="float:left;clear:none;">'||v_search.submission_date||'</div>');
end loop;
htp.p('</div>');
end;
end;Ps. hope I understood you correctly, also this code is untested.. but I hope it can still help.
Edited by: Olav Alexander Mjelde on May 12, 2010 9:36 AM -
Query Report - To display additional column in list selection box.
Hi,
There is query report where i want to display the additional column in list selection.
Below is the system query report, where parameter passed is card code.
When the cardcode - list selection is clicked system displays 2 columns i.e. Customer Code & No. of Records.
Now in the same list selection; is it possible to display the customer name along with cardcode only for reference.
SELECT T0.DocDate, T1.SlpName, T2.Name, T0.DocDueDate, T0.DocNum, (CASE WHEN T0.DocStatus = 'O' THEN 'Open' ELSE 'Closed' END) AS Status, T0.DocTotal FROM OQUT T0 LEFT JOIN OSLP T1 ON T0.SlpCode = T1.SlpCode LEFT JOIN OCPR T2 ON T0.CntctCode = T2.CntctCode WHERE T0.CardCode = N'[%0]' ORDER BY T0.DocNum DESC
Kindly let me know the details.
Thanks & Regards,
Yogesh JadavHi Yogesh Jadav,
The answer is NO. You may only display either code or name but not both.
Thanks,
Gordon -
Content Query display multiple columns
Hello,
I am using a content query web part (in sharepoint 2013) to display a list from another site. The problem is that I don't see enough info from that list because I can display maximum 2 columns.
Is it possible to display more columns from this list with the Content query web part? I would like to display all the columns from this list. Do i need to make a display template or something?
Thanks.You have to customize the CQWP.
Please check the below link
http://pholpar.wordpress.com/2010/01/21/displaying-results-in-multiple-columns-using-the-content-query-web-part/
Other option is you ca use Dataview webpart to show the list details from one site to other site
http://www.learningsharepoint.com/2012/08/12/sharepoint-2013-add-dataview-webpart-with-sharepoint-designer-2013/
http://sharepointgeorge.com/2009/display-sharepoint-list-site-data-view-web-part/
MCTS,MCPD Sharepoint 2010. My Blog-
http://www.sharepoint-journey.com
If a post answers your question, please click "Mark As Answer" on that post and "Vote as Helpful -
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
-
How to display a 1 to many query result in a single row?
Hi,
I want to display a 1 to many relationship in a query in just one row. The current result is that I get more than 1 rows. How can I display it in one column with the additional attribute in a column, without repeating? Thank you.
Select s.student, t.teacher from student_table s, teacher_table t where s.id = t.student_id
Result
Student Teacher
John Doe Larry Woe
John Doe Mary Moe
I would rather get a result like this:
Result
Student Teacher 1 Teacher 2
John Doe Larry Woe Mary Woe
Edited by: Samantha on May 18, 2011 2:48 PMHi,
Will all Students have exactly two Teachers?
If not picture your sample with two more Students.
One having 1 Teacher
One having N Teachers
Think about N, what will it be? - How would you create a table with N columns?
If you can't easily answer above, re-consider what you are trying.
That said, it could still be done - even if all Students do not have exactly two Teachers - and is called Pivot a dynamic number of columns.
Examples are in FAQ
SQL and PL/SQL FAQ
Still a bad idea, with or without known number of teachers
Regards
Peter -
Display a column as row with same row names.
Hi,
My belwo query displaying o/p in this format.I need to conver a row with appriate colmn value (see the required o/p).
could some help.
current o/p
TEST_SESSION_ID ROSTER_DOMAIN_NAME TO_CHAR(A.SCORE) SEM
4087 AR - Integers and Fractions 5.148757270620481 1
4087 AR - Decimal Numbers 5.5597596042656825 2required o/p format
TEST_SESSION_ID AR - Integers and Fractions AR - Decimal Numbers sem-AR - sem
Integers and Fractions AR - Decimal Numbers
4087 5.148757270620481 5.5597596042656825 1 2ROSTER_DOMAIN_NAME are not staticks.I tcould be increase .some times it could have 20 names.Since i can t use decode or case with statically .can some one help on this.
query
SELECT a.test_session_id,c.roster_domain_name,to_char(a.score),a.sem FROM
test_session_detail a,test_session b ,test_detail c
WHERE a.test_session_id = b.test_session_id
AND c.test_detail_id = a.test_detail_id
AND exists (
select td.test_detail_id
from test_detail td
where domain_map_id is not null
and c.test_detail_id =td.test_detail_id
and domain_map_id in('303','306','305','304'))
AND b.test_session_id in ('4087')
AND domain_group_id NOT IN (
SELECT domain_group_id
FROM test_session_detail a,test_session b
WHERE a.test_session_id = b.test_session_id
AND a.domain_group_id is not null
AND b.test_session_status_id = 4
AND a.test_session_status_id <> 3
AND b.test_session_id IN ('4087'))Ok, the problem here is that you want a dynamic pivot of data and you also want to use some of the data as the column names.
SQL requires that the columns to be retrieved are known at query parse time, i.e. before any data is fetched, so it's not easily possible to have dynamic column names done in a single query.
The general steps in executing a query are...
1. Submit SQL query (Open Query)
2. SQL Query Parsed
3. SQL Query Executed
4. Row Fetched
5. Repeat step 4 until no more rows
6. Close QuerySo, as you can see no data is fetched until step 4, but, at Step 2, the SQL engine needs to have parsed the query and already know what columns and data types are going to be returned.
An example of how something similar can be achieved is given on this thread:
How to pipeline a function with a dynamic number of columns?
But that may be a little too complex to implement.
What you are really wanting is something at the front end reporting side of things.
Ideally, this is the task of a reporting tool, not of the SQL engine which is retrieving the data. -
All,
Could anyone please clarify me on , how we can count the column's which were used in a query.
Ex: SELECT ENAME, EMPNO, SAL , JOB FROM EMP;
--Here in the above query, I have taken 4 columns(counted manually) . Instead of counting it manually is there any other way.
ThanksIt sounds like you're creating dynamic SQL. Why are you doing that? Dynamic SQL's would seem to indicate you don't know the structure of your own database or that your application design is trying to be generic rather than being designed in proper modularized units (1 unit does 1 task, not multiple generic tasks). 99.999% of the time, people using dynamic SQL indicates that they are misusing the database or haven't designed things properly.
If there's really a valid reason for using dynamic SQL, then of course you can do it properly and use all the features of Oracle to get information about the dynamic SQL, but that means not using something as poor as EXECUTE IMMEDIATE (which is often abused by most people), or trying to use ref cursors within PL/SQL (which are more intended for 3rd party application layers). The power of dynamic SQL is gained from using the DBMS_SQL package... as in the following simplistic example...
SQL> set serverout on
SQL> create or replace procedure run_query(p_sql IN VARCHAR2) is
2 v_v_val varchar2(4000);
3 v_n_val number;
4 v_d_val date;
5 v_ret number;
6 c number;
7 d number;
8 col_cnt integer;
9 f boolean;
10 rec_tab dbms_sql.desc_tab;
11 col_num number;
12 v_rowcount number := 0;
13 begin
14 -- create a cursor
15 c := dbms_sql.open_cursor;
16 -- parse the SQL statement into the cursor
17 dbms_sql.parse(c, p_sql, dbms_sql.native);
18 -- execute the cursor
19 d := dbms_sql.execute(c);
20 --
21 -- Describe the columns returned by the SQL statement
22 dbms_sql.describe_columns(c, col_cnt, rec_tab);
23 --
24 -- Bind local return variables to the various columns based on their types
25
26 dbms_output.put_line('Number of columns in query : '||col_cnt);
27 for j in 1..col_cnt
28 loop
29 case rec_tab(j).col_type
30 when 1 then dbms_sql.define_column(c,j,v_v_val,2000); -- Varchar2
31 when 2 then dbms_sql.define_column(c,j,v_n_val); -- Number
32 when 12 then dbms_sql.define_column(c,j,v_d_val); -- Date
33 else
34 dbms_sql.define_column(c,j,v_v_val,2000); -- Any other type return as varchar2
35 end case;
36 end loop;
37 --
38 -- Display what columns are being returned...
39 dbms_output.put_line('-- Columns --');
40 for j in 1..col_cnt
41 loop
42 dbms_output.put_line(rec_tab(j).col_name||' - '||case rec_tab(j).col_type when 1 then 'VARCHAR2'
43 when 2 then 'NUMBER'
44 when 12 then 'DATE'
45 else 'Other' end);
46 end loop;
47 dbms_output.put_line('-------------');
48 --
49 -- This part outputs the DATA
50 loop
51 -- Fetch a row of data through the cursor
52 v_ret := dbms_sql.fetch_rows(c);
53 -- Exit when no more rows
54 exit when v_ret = 0;
55 v_rowcount := v_rowcount + 1;
56 dbms_output.put_line('Row: '||v_rowcount);
57 dbms_output.put_line('--------------');
58 -- Fetch the value of each column from the row
59 for j in 1..col_cnt
60 loop
61 -- Fetch each column into the correct data type based on the description of the column
62 case rec_tab(j).col_type
63 when 1 then dbms_sql.column_value(c,j,v_v_val);
64 dbms_output.put_line(rec_tab(j).col_name||' : '||v_v_val);
65 when 2 then dbms_sql.column_value(c,j,v_n_val);
66 dbms_output.put_line(rec_tab(j).col_name||' : '||v_n_val);
67 when 12 then dbms_sql.column_value(c,j,v_d_val);
68 dbms_output.put_line(rec_tab(j).col_name||' : '||to_char(v_d_val,'DD/MM/YYYY HH24:MI:SS'));
69 else
70 dbms_sql.column_value(c,j,v_v_val);
71 dbms_output.put_line(rec_tab(j).col_name||' : '||v_v_val);
72 end case;
73 end loop;
74 dbms_output.put_line('--------------');
75 end loop;
76 --
77 -- Close the cursor now we have finished with it
78 dbms_sql.close_cursor(c);
79 END;
80 /
Procedure created.
SQL> exec run_query('select empno, ename, deptno, sal from emp where deptno = 10');
Number of columns in query : 4
-- Columns --
EMPNO - NUMBER
ENAME - VARCHAR2
DEPTNO - NUMBER
SAL - NUMBER
Row: 1
EMPNO : 7782
ENAME : CLARK
DEPTNO : 10
SAL : 2450
Row: 2
EMPNO : 7839
ENAME : KING
DEPTNO : 10
SAL : 5000
Row: 3
EMPNO : 7934
ENAME : MILLER
DEPTNO : 10
SAL : 1300
PL/SQL procedure successfully completed.
SQL> -
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 -
How Can i add "DateDiff(day, T0.DueDate" as a column in this query?
How Can i add "DateDiff(day, T0.DueDate" as a column in this query?
SELECT T1.CardCode, T1.CardName, T1.CreditLine, T0.RefDate, T0.Ref1 'Document Number',
CASE WHEN T0.TransType=13 THEN 'Invoice'
WHEN T0.TransType=14 THEN 'Credit Note'
WHEN T0.TransType=30 THEN 'Journal'
WHEN T0.TransType=24 THEN 'Receipt'
END AS 'Document Type',
T0.DueDate, (T0.Debit- T0.Credit) 'Balance'
,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')<=-1),0) 'Future'
,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>=0 and DateDiff(day, T0.DueDate,'[%1]')<=30),0) 'Current'
,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>30 and DateDiff(day, T0.DueDate,'[%1]')<=60),0) '31-60 Days'
,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>60 and DateDiff(day, T0.DueDate,'[%1]')<=90),0) '61-90 Days'
,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>90 and DateDiff(day, T0.DueDate,'[%1]')<=120),0) '91-120 Days'
,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>=121),0) '121+ Days'
FROM JDT1 T0 INNER JOIN OCRD T1 ON T0.ShortName = T1.CardCode
WHERE (T0.MthDate IS NULL OR T0.MthDate > [%1]) AND T0.RefDate <= [%1] AND T1.CardType = 'C'
ORDER BY T1.CardCode, T0.DueDate, T0.Ref1Hi,
As you mentioned not possible to assign the dynamic column in the query.
will give you example for generate a dynamic column name in SQL query, using this example you can achieve your requirement.
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(C.Name)
from [History]
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT [Date],' + @cols +'
from
select [Date], Name, Value
from [History]
) x
pivot
max(value)
for Name in (' + @cols + ')
) p '
execute(@query) -
Hi, I am trying to do a pivot report, first I did a simple pivot hard-coding the columns that I was about to use but, it is not convenient so I was asked to do a dynamic report where the columns were selected by a sub-query so I followed the solution from this post
Pivot query using XML option in APEX , but I get this error ORA-00932: inconsistent datatypes: expected - got CLOB, now I know that by default that query is set to return CLOB, but the thing is that when I specify the return value to varchar2 my browser freezes and I cannot go any further than that I need to reboot my browser, I'm using Oracle 11g and APEX 3.2.1 here is my query
SELECT
xmlserialize(CONTENT DEPARTMENT_XML as varchar2(4000)) XML
FROM
SELECT
DEPARTMENT,
S_GROUP AS "S GROUP",
S_GROUP
FROM MYTABLE where PER = 'BNA' and department not like 'SI%'
PIVOT XML(
COUNT(S_GROUP)
FOR DEPARTMENT
IN (select distinct department from MYTABLE ) )
ORDER BY 1
Thank you.Because execuitng the query without the
ROW_NUMBER gives the results in milliseconds
but the row_number takes it 7+ min.I think you mean that executing the query without ROW_NUMBER gives the first rows in milliseconds. However, if you wait until the last row, you may find that it takes several minutes as well. If this is not the case, please post some more details.
And, as BluShadow already said, an additional ordering takes some time, so it will be a little slower, but probably not this much. If you really want to know where time is being spent, then I suggest to take a look at [url http://forums.oracle.com/forums/thread.jspa?threadID=501834&tstart=0]this thread, and start measuring.
Regards,
Rob.
Maybe you are looking for
-
I am trying to download iTunes on my new desktop computer (Windows 7, 64 bit). It starts installing, and then stops with the message- "The System Administrator has set policies to prevent this installation." This is a stand alone computer and I am t
-
I have a new Macbook Air 2012, Apple TV 2 and I have tried wired and wireless connections both still result in stuttering during video airplay to the ATV2. I have even bought a new Airport Extreme Router just to confirm it is not the router and it st
-
ORA-01152: file 1 was not restored from a sufficiently old backup
Hi, I have restored the control file from auto-backup, but some of my archive logs are missing... when I am recovering it as RECOVER DATABASE UNTIL CANCEL USING BACKUP CONTROLFILE; ORA-00279: change 37158334186 generated at 02/19/2012 02:53:11 needed
-
Keynote ios8 inserting wrong images in slides
My students are tapping an image to insert and it inserts the image next to it. What can be done to fix this?
-
How to print Pdf files using Adobe Reader
How to print Pdf files using Adobe Reader