Dynamic column selection
I want to select specific columns from a table dynamically which are basically the columns returned by quering the user_tab_columns data dictionary which in turn has to satisfy certain condition for me.
So, what I want to do is something like:
SELECT b.(dynamic column list from a)
FROM b,
(SELECT column_name FROM user_tab_columns WHERE table_name='STH' AND ........) a
any help will be greatly appreciated.
sql>create or replace procedure p_dynamic_sql
2 is
3 v_sql varchar2(4000);
4 begin
5 v_sql := 'select ';
6 for r in (select column_name
7 from user_tab_cols
8 where table_name = 'EMP'
9 and column_name like 'E%') loop
10 v_sql := v_sql || r.column_name || ',';
11 end loop;
12 v_sql := rtrim(v_sql, ',') || ' from emp';
13 dbms_output.put_line( v_sql );
14 -- do something with SQL (open cursor, etc.)
15 end;
16 /
Procedure created.
sql>exec p_dynamic_sql
select EMPNO,ENAME from emp
PL/SQL procedure successfully completed.
Similar Messages
-
Hi All,
Suppose I have table, whose structure changes frequently on daily basis.
For eg. desc my_table gives you following column name on Day 1
SQL > desc my_table;
Output
Name
Age
Phone
On Day 2, two more columns are added, viz, Address and Salary.
SQL > desc my_table;
Output
Name
Age
Phone
Address
Salary
Now I want to create an Dynnamic RTF report which would fetch data from ALL columns from my_table on daily basis. For that I have defined a concurrent program with XML as output type and have attached a data template/data definition to it which takes in XML as input and gives final output of conc program in EXCEL layout. I am able to do this for constant number of columns, but dont know how to do it when the number of columns to be displayed changes dynamically.
For Day 1 my XML file should be like this.
<?xml version="1.0" encoding="UTF-8"?>
<dataTemplate name="XYZ" description="iExpenses Report" Version="1.0">
<dataQuery>
<sqlStatement name="Q2">
<![CDATA[
SELECT Name
,Age
,Phone
FROM my_table
]]>
</sqlStatement>
</dataQuery>
<dataStructure>
<group name="G_my_table" source="Q2">
<element name="Name" value="Name" />
<element name="Age" value="Age" />
<element name="Phone" value="Phone" />
</group>
</dataStructure>
</dataTemplate>
And my Day 1, EXCEL output from RTF template should be like this.
Name Age Phone
Swapnill 23 12345
For Day 2 my XML file should be like this. With 2 new columns selected in SELECT clause.
<?xml version="1.0" encoding="UTF-8"?>
<dataTemplate name="XYZ" description="iExpenses Report" Version="1.0">
<dataQuery>
<sqlStatement name="Q2">
<![CDATA[
SELECT Name
,Age
,Phone
,Address
,Salary
FROM my_table
]]>
</sqlStatement>
</dataQuery>
<dataStructure>
<group name="G_my_table" source="Q2">
<element name="Name" value="Name" />
<element name="Age" value="Age" />
<element name="Phone" value="Phone" />
<element name="Address" value="Address" />
<element name="Salary" value="Salary" />
</group>
</dataStructure>
</dataTemplate>
And my Day 2, EXCEL output from RTF template should be like this.
Name Age Phone Address Salary
Swapnill 23 12345 Madrid 100000
Now, I dont know below things.
Make the XML dynamic as in on Day 1 there must be 3 columns in the SELECT statement and on Day 2, 5 columns. I want to create one dynamic XML which should not be required to be changed if new columns are added in my_table. I dont know how to create this query and also create their corresponding elements below.
Make the RTF template dyanamic as in Day1 there must 3 columns in EXCEL output and on Day 2, 5 columns. I want to create a Dynamic RTF template which would show all the columns selected in Dynamic XML.I dont know how the RTF will create new XML tags and how it will know where to place it in the report. Means, I can create RTF template on Day 1, by loading XML data for 3 columns and placing 3 XML tags in template. But how will it create and place tags for new columns on Day 2?
Hope, you got my requirement, its a challenging one. Please let me know how I can implement the required solution using RTF dynamically without any manual intervention.
Regards,
Swapnil K.
Message was edited by: SwapnilKHi All,
I am able to fulfil above requirement. Now I am stuck at below point. Need your help!
Is there any way to UPDATE the XML file attached to a Data Definition (XML Publisher > Data Definition) using a standard package or procedure call or may be an API from backend? I am creating an XML dynamically and I want to attach it to its Data Definition programmatically using SQL.
Please let me know if there is any oracle functionality to do this.
If not, please let me know the standard directories on application/database server where the XML files attached to Data Definitions are stored.
For eg, /$APPL_TOP/ar/1.0/sql or something.
Regards,
Swapnil K. -
Dynamic column selection while running report
Can any one explain how to get the following functionality in report:
I have a cube with following fields:(with depriciaated amounts)
Plant Mat# Fiscper Jan Feb March April May June July Aug Sep Oct Nov Dec
==== ==== ===== ==== ==== ===== ==== ==== ===== ==== ==== ===== ==== ==== ====
P1 M1 03/2009 $100 $90 $80
P1 M1 04/2009 $100 $90 $80 $70
P2 M2 04/2009 $10 $9 $8
P2 M2 04/2009 $10 $9 $8 $7
When I run the report with Fiscper as selection, ie 04/2009, I shoud get the report displayed only April column
Report out put: (Only April column should be displayed)
Plant Mat# Fiscper April
==== ==== ===== ====
P1 M1 04/2009 $70
P2 M2 04/2009 $7
When I run the report with Fiscper as selection, ie 03/2009, I shoud get the report displayed only March column
Report out put: (Only March column should be displayed)
Plant Mat# Fiscper March
==== ==== ===== ====
P1 M1 04/2009 $80
P2 M2 04/2009 $8
Can any explain how to desing this in query designer?
Thanks,
PVcreate new selection
drag and drop the kf
drag and drop calmonth
create formula variable for calmonth using type as "customer exit"
now based on the fiscperiod you can fill calmonth in customer exit which will give you desired output
you can use text variable if you want the heading for the KF to be dynamic. -
BIEE & BI Publisher parameter & dynamic column selection
Hi Gurus!
I want to create a SQL Query on the BIServer from BIPublisher that create a data set that dynamically return a different column based on a BI Publisher parameter (that i will feed from a Dashboard prompt);
I've tried to write something like the follow query, but always it returns errors...
select case when :Parameter='Measure1' then mytable.measure1 else mytable.measure2 end as Measure, mytable.dim1 as Dim from mytable where mytable.year=:YearParam;
the parameter in the where works, but I'm not able to use the parameter in the case clause.
Is it possible to use the parameter in the case statement?
If i write a similar sql against a RDBMS it works great..
I'n on a 10.1.3.4.1
Any suggestion?
Regards,
DanieleYou might use the indexcol function for this purpose.
http://download.oracle.com/docs/cd/E12096_01/books/admintool/admintool_SQL15.html
In the document, you have a hierarchy example.
Success
Nico -
Dynamic column selection based on login in BI Answers
Hi
I have a dimension with manager level 1 to 10, based on the user login, I want to display the table with the column (level 1 or level n) dynamically ( ex: if the user is in manager level n, display column level n with other data in the table). P.S. there are more than 10000+ users, so I can't customize each user.
can you please let me know if this is possible and how to do it?
Thanks a lot,You might use the indexcol function for this purpose.
http://download.oracle.com/docs/cd/E12096_01/books/admintool/admintool_SQL15.html
In the document, you have a hierarchy example.
Success
Nico -
Cannot use alias for dynamic column name in SELECT statement
Hi,
I want to retrieve values from several tables by using dynamic column & table name as below:
DATA: tbl_name(30) TYPE c VALUE '/bic/tbi_srcsys', " staticly initialized for this example
col_name(30) TYPE c VALUE '/bic/bi_srcsys'. " staticly initialized for this example
SELECT (col_name) INTO CORRESPONDING FIELDS OF TABLE it_values FROM (tbl_name).
The internal table "it_values" does not contain a field named "/bic/bi_srcsys", instead it has another generic field "value" so that the above code can be applied to other tables. I tried to use alias (AS) as below:
SELECT (col_name) AS value INTO CORRESPONDING FIELDS OF TABLE it_values FROM (tbl_name).
But this cannot work. I know that there are other ways to solve this problem, such as by using a single field in SELECT .. ENDSELECT and subsequently appending it to the work area and internal table as below:
SELECT (col_name) INTO (lv_value) FROM (tbl_name).
wa_value-value = lv_value.
APPEND wa_value TO it_values.
ENDSELECT.
Just wonder if there is any other more elegant workaround, because I might have several other fields instead of only one?
Thanks.
Regards,
Joon MengHi Suhas,
thanks for the quick reply.
Sorry that I have not well described the structure of the internal table "it_values". This internal table contains several other fields (key, type, value, etc.).
I guess that the following code
SELECT (col_name) INTO TABLE it_values FROM (tbl_name).
works if the internal table only has one field (value) or the field "value" is in the first position, right?
In this case, I need to fill the "value" field of internal table it_values (ignore the other fields like type, key) with values retrieved from (col_name) of the DDIC table.
Looking forward to your reply.
BR,
Joon Meng -
How can we get Dynamic columns and data with RTF Templates in BI Publisher
How can we get Dynamic columns and data with RTf Templates.
My requirement is :
create table xxinv_item_pei_taginfo(item_id number,
Organization_id number,
item varchar2(4000),
record_type varchar2(4000),
record_value CLOB,
State varchar2(4000));
insert into xxinv_item_pei_taginfo values( 493991 ,224, '1265-D30', 'USES','fever','TX');
insert into xxinv_item_pei_taginfo values( 493991 ,224, '1265-D30', 'HOW TO USE','one tablet daily','TX');
insert into xxinv_item_pei_taginfo values( 493991 ,224, '1265-D30', 'SIDE EFFECTS','XYZ','TX');
insert into xxinv_item_pei_taginfo values( 493991 ,224, '1265-D30', 'DRUG INTERACTION','ABC','TX');
insert into xxinv_item_pei_taginfo values( 493991 ,224, '1265-D30', 'OVERDOSE','Go and see doctor','TX');
insert into xxinv_item_pei_taginfo values( 493991 ,224, '1265-D30', 'NOTES','Take after meal','TX');
select * from xxinv_item_pei_taginfo;
Item id Org Id Item Record_type Record_value State
493991 224 1265-D30 USES fever TX
493991 224 1265-D30 HOW TO USE one tablet daily TX
493991 224 1265-D30 SIDE EFFECTS XYZ TX
493991 224 1265-D30 DRUG INTERACTION ABC TX
493991 224 1265-D30 OVERDOSE Go and see doctor TX
493991 224 1265-D30 NOTES Take after meal TX
Above is my data
I have to fetch the record_type from a lookup where I can have any of the record type, sometime USES, HOW TO USE, SIDE EFFECTS and sometimes some other set of record types
In my report I have to get these record typpes as field name dynamically whichever is available in that lookup and record values against them.
its a BI Publisher report.
please suggestif you have data in db then you can create xml with needed structure
and so you can create bip report
do you have errors or .... ? -
How to change recordset bahaviour to accept dynamic column names in the where clause
Hi
im using php-mysql and i make a recordset and i want to make the column names in the where clause to be dynamic like
"select id,name from mytable where $tablename-$myvar";
but when i do this my i break the recordset and it disappear
and when i use variables from advanced recordset it only dynamic for the value of the column not for the column name
and when i write the column name to dynamic as above by hand it truns a red exclamation mark on the server behaviour panel
so i think the only way is to change the recordset behaviour is it? if so How to make it accept dynamic column names?
thanks in advance.As bregent has already explained to you, customizing the recordset code will result in Dreamweaver no longer recognizing the server behavior. This isn't a problem, but it does mean that you need to lay out your dynamic text with the Bindings panel before making any changes. Once you have changed the recordset code, the Bindings panel will no longer recognize the recordset fields.
Using a variable to choose a column name is quite simple, but you need to take some security measures to ensure that the value passed through the query string isn't attempting SQL injection. An effective way of doing this is to create an array of acceptable column names, and check that the value matches.
// create array of acceptable values
$valid = array('column_name1', 'column_name2', 'column_name3');
// if the query string contains an acceptable column name, use it
if (isset($_GET['colname']) && in_array($_GET['colname'], $valid)) {
$col = $GET['colname'];
} else {
// set a default value if the submitted one was invalid
$col = 'column_name1'
You can then use $col directly in the SQL query. -
Im getting an error when running a procedure that includes this code.
I need to select from a dynamic column name and save the result in a variable, but seem to be having trouble with the values being fed to sp_executesql
DECLARE @retval AS DECIMAL(12,2)
DECLARE @MonthVal VARCHAR(20), @SpreadKeyVal INT
DECLARE @sqlcmd AS NVARCHAR(150)
DECLARE @paramdef NVARCHAR(150)
SET @MonthVal = 'Month' + CAST(@MonthNumber AS VARCHAR(2) );
SET @SpreadKeyVal = @SpreadKey; --CAST(@SpreadKey AS VARCHAR(10) );
SET @sqlcmd = N' SELECT @retvalout = @MonthVal FROM dbo.CourseSpread WHERE CourseSpreadId = @SpreadKeyVal';
SET @paramdef = N'@MonthVal VARCHAR(20), @SpreadKeyVal INT, @retvalout DECIMAL(12,2) OUTPUT'
--default
SET @retval = 0.0;
EXECUTE sys.sp_executesql @sqlcmd,@paramdef, @MonthVal = 'Month4',@SpreadKeyVal = 1, @retvalout = @retval OUTPUT;
SELECT @retval
DECLARE @return_value DECIMAL(12,2)
EXEC @return_value = [dbo].[GetSpreadValueByMonthNumber]
@SpreadKey = 1,
@MonthNumber = 4
SELECT 'Return Value' = @return_value
Msg 8114, Level 16, State 5, Line 1
Error converting data type varchar to numeric.Please follow basic Netiquette and post the DDL we need to answer this. Follow industry and ANSI/ISO standards in your data. You should follow ISO-11179 rules for naming data elements. You should follow ISO-8601 rules for displaying temporal data. We need
to know the data types, keys and constraints on the table. Avoid dialect in favor of ANSI/ISO Standard SQL. And you need to read and download the PDF for:
https://www.simple-talk.com/books/sql-books/119-sql-code-smells/
>> I need to select from a dynamic column name and save the result in a variable, but seem to be having trouble with the values being fed to sp_executesql <<
This is so very, very wrong! A column is an attribute of an entity. The idea that you are so screwed up that you have no idea if you want
the shoe size, the phone number or something else at run time of this entity.
In Software Engineering we have a principle called cohesion that says a model should do one and only one task, have one and only one entry point, and one and only one exit point.
Hey, on a scale from 1 to 10, what color is your favorite letter of the alphabet? Yes, your mindset is that level of sillyity and absurdity.
Do you know that SQL is a declarative language? This family of languages does not use local variables!
Now think about “month_val” and what it means. A month is a temporal unit of measurement, so this is as silly as saying “liter_val” in your code. Why did you use “sp_” on a procedure? It has special meaning in T-SQL.
Think about how silly this is:
SET @month_val = 'Month' + CAST(@month_nbr AS VARCHAR(2));
We do not do display formatting in a query. This is a violation of at the tiered architecture principle. We have a presentation layer. But more than that, the INTERVAL temporal data type is a {year-month} and never just a month. This is fundamental.
We need to see the DDL so we can re-write this mess. Want to fix it or not?
--CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
in Sets / Trees and Hierarchies in SQL -
How to get the dynamic columns in UWL portal
Hi All,
I am working on UWL Portal. I am new to UWL. I have down loaded uwl.standard XML file and costomized for getting the values for "select a Subview" dropdown and I am able to see the values in the dropdown. Now my requirement is to get the dynamic columns based on the selection from dropdown value.
can any body suggest on how to get the dynamic columns in UWL portal.Hi Manorama,
1) If you have already created a portal system as mentioned in following blog
/people/marcel.salein/blog/2007/03/14/how-to-create-a-portal-system-for-using-it-in-visual-composer
2) If not, then try to create the same. Do not forgot to give the Alias name .
3) After creating a system, log on to the VC, Create one iView.
4) Now Click on "Find Data" button from the list which you can view in right side to Visual composer screen.
5) After clicking on "Find Data" button, it will ask for System. If you have created your system correctly and Alias name is given properly, then your mentioned Alias name is appeared in that list.
6) Select your system Alias name and perform search.
7) It will display all the BAPIs and RFCs in your systems.
8) Select required BAPI and develop the VC application.
Please let me know if you any further problems.
Thanks,
Prashant
Do reward points for useful answers. -
DataGrid with dynamic columns & renderers
I'm developing using Flash Builder 4 & Flex SDK 4.1.
I need to manage very dynamic DataGrid components and keep their definitions, which are all part of a complex item renderer of an Offers list.
The objects structure is simplified as follows -
Data: Model --> Offers ArrayCollection --> Offer VO --> DataGrid data ArrayCollection & DataGrid columns Array
View: List --> Offer Item Renderer --> DataGrid
1. Since the DataGrid's columns property accepts only an Array (not ArrayCollection), it seems like Data Binding for defining the columns is very problematic.
I tried to bind it to the source property of an ArrayCollection that would keep my columns definitions, but it didn't really work (mainly header display bugs).
What is the recommended way to keep the dynamic columns definition of a DataGrid?
2. Each column can have a set of dynamic properties, so I created a "mutant" - Column VO that extends DataGridColumn and got a dynamic properties ArrayCollection on it.
The columns got a custom header renderer that includes an icon when there are properties.
The header renderers got 4 main states (NotSelectedWithProperties, SelectedWithProperties, NotSelectedWithoutProperties & SelectedWithoutProperties).
However, the header renderer area seems a bit buggy when maintaning dynamic columns.
Any thoughts on the subject?
3. Anyway, I ended up recreating the DataGrid's columns Array very often (copying the columns definition on the offer's item renderer's dataChange event handler).
Note that the dynamic properties can be edited when the column is selected and I copy their values from the view back to the model when entering the state NotSelectedWithProperties.
This feels way too complicated and I really try to keep it simple, inspite of the required complexity.
Does anyone have better ideas?
4. In some cases the column's item renderer should also be modified into another DataGrid (grid-in-grid).
I used the MXDataGridItemRenderer with a DataGrid and included an ArrayCollection for the "newValue" returned by the editor.
(I use RendererIsEditor=true and on updateComplete populate that variable with the DataGrid's dataProvider contents)
When needed, I loop though the data objects of the parent DataGrid and populate the related field with an ArrayCollection of key-value objects that are displayed on the internal DataGrid.
After adding this feature I encounter very strange bugs -
a. After editing the grid-in-grid values and changing the column's state (selecting & deselecting), I get the following exception:
ArgumentError. Error #2025: The supplied DisplayObject must be a child of the caller.
at flash.display::DisplayObjectContainer/setChildIndex()
at mx.core::UIComponent/setChildIndex().......6993....
All I could find about this is that it might be related to some context error or something, but I'm really stuck on this one.
b. Sometimes another column might copy value from one row to another, running over the previous value.
I'm not sure exactly what sequence of actions causes this behavior, but it's related to that itemRenderer for sure.
c. Switching places with a column that uses the grid item renderer (headerShift) causes a stak overflow of StyleManager that tried to get style from the DataGridItemRenderer. This one I just found out, but couldn't reproduce a second time... strange!
I'm pretty sure this caused another problem that I don't remember at the moment.
The bottom line is that there got to be a better way to implement this feature within this already-complicated environment.
Maybe I'm doing something very wrong here...
Please advice and thanks for reading all this.Update on item 4a -
This was a major issue (the main reason for opening this thread really) and I managed to resolve it!
As part of my application, I override the default DataGrid behavior for column selection (headerRelease event).
Instead of sorting, I change the column's header looks and define it as Selected (for showing its dynamic properties and enable its deletion).
At first I did this by setting styles, but the look didn't refresh unless I created a new instance of the header renderer.
Later I changed thi behavior to work with states, but I left the new header renderer instance creation commands and those lines created all the mess!
Conclusion -
If you define a custom header renderer for your datagrid column and then a custom item renderer, don't create a new instance of your header renderer!
It would still be nice to get some response for the other issues I raised.
Thanks and have a nice week. -
I created a line chart with the following sql statement:
select null link, periode_jaar, sum(totaal) total from V_KPL_VZ_OWB@rapportage_dwhtest
where periode_jaar = (Select max(periode_jaar) from V_KPL_VZ_OWB@rapportage_dwhtest)
group by periode_jaar
order by periode_jaar
In the legend of the chart the line is named total. I would like have it named for example: Total 2009
So how i create the dynamic column? Any ideas? Tnx in advnacedtnx for helping, i posted my xml code below where to put the tag: <format>{%Name} ({%Value})</format>
i assume i have to replace %Name with my sirie name and the %Value with the name i wanted?
Is it possible to replace %Value with an item like :p1_year
<?xml version = "1.0" encoding="utf-8" standalone = "yes"?>
<root>
<type>
<chart type="2DLine">
<animation enabled="yes" appearance="size" speed="10" />
<hints auto_size="yes">
<text><![CDATA[{NAME}, {VALUE}]]></text>
<font type="Verdana" size="10" color="0x000000" />
</hints>
<names show="yes" width="150" placement="chart" position="bottom" >
<font type="Verdana" size="10" color="0x000000" />
</names>
<values show="no" prefix="" postfix="%" decimal_separator="," decimal_places="0" />
<arguments show="no" />
<line_chart left_space="5" right_space="5">
<block_names enabled="no" />
</line_chart>
</chart>
<workspace>
<background enabled="yes" type="solid" color="0xffffff" alpha="0" />
<base_area enabled="no" />
<chart_area enabled="yes" x="80" y="50" width="380" height="280" deep="0">
<background enabled="no"/>
<border enabled="yes" size="1"/>
</chart_area>
<x_axis name="Jaar" smart="yes" position="center_bottom" >
<font type="Verdana" size="14" color="0x000000" bold="no" align="center" />
</x_axis>
<y_axis name="%" smart="yes" position="left_center" >
<font type="Verdana" size="14" color="0x000000" bold="no" align="center" />
</y_axis>
<grid>
<values />
</grid>
</workspace>
<legend enabled="yes" x="480" y="50">
<font type="Verdana" size="10" color="0x000000" />
</names>
<values enabled="YES"/>
<scroller enabled="no"/>
<header enabled="no"/>
<background alpha="0"/>
</legend>
</type>
#DATA#
</root> -
Dynamic column heading in csv export not working
Hi,
I have a SQL report where the column headings are defined dynamically. for an example let's say I have a report
SELECT NAME, TODAY'S_DATE FROM TABLE A.
Under report attribute column I have defined column heading as "&P_todays_date.”. This item has source value “Select sysdate from dual. When I export the data into csv file the dynamic column headings are coming as blank.
Any suggestions?
Thanks,
ManishYou are posting this question in the PeopleSoft forums. I think it belongs in the BI section:
https://forums.oracle.com/forums/category.jspa?categoryID=16 -
Dynamic Column Selector in OBIEE - Solution required
Hello Experts,
I am pretty new to OBIEE. Please help me to get OBIEE solution for below requirement.
I have one 25 column dimension table in database. Created OBIEE .rpd file and published in BI server. Now I need to provide one user interface in which user should be able to chose any number of columns of his choice and he should get record set of those selected columns. Something in my mind is like this.
I should be providing list of 25 column names with check box to select one or many. Assuming that if user selects Col1, Col3,Col5 and Col7 then he should get the result in excel file with record set of those 4 columns.
I am using OBIEE 10g.
Any solution for this is highly appreciated.
Edited by: user7850154 on Dec 5, 2010 9:22 AMuser,
Usually, dynamic column seletor is implemented through "column selector view" available within compund layout of OBIEE Answers.
But, it does allow you to select only single column rather than multiple columns - which in your case is required.
J
-bifacts
http://www.obinotes.com -
Dynamic column names in Oracle
HI SOS!! calling for help...
i am trying to query the following. I want to remove the duplicates in the ID, and combine them into one... While doing so, I want to keep the data as it is by creating dynamic columns reason_1, reason_2, reason_3 with their corresponding TIME. In case of same reasons, I want to add the TIME. The database is as follows:
ID REASON TIME
A 41A.......... 27
A 93K..........16
B 89C...........3
B 93K...........7
B 48C.......... 4
C 93K.......... 24
C 93K.......... 7
C 48C.........10
Expected Result is
ID REASON_1......TIME_1.... REASON_2...TIME_2....REASON_3.........TIME_3
A........ 41A............ 27........... 93K............16
B........ 89C............ 3............ 93K............7...........48C.................. 4
C........ 93K........... 31.......... 48C..............10
Would be grateful if someone could try helping me out of this as early as possible.
Edited by: 968125 on Oct 28, 2012 11:01 PMYou still haven't made it clear what the requirement is.
Is there a maximum number of reasons that can occur per ID? If so, you can code the pivoting of your data with something like:
SQL> ed
Wrote file afiedt.buf
1 with t as (select 'A' as ID, '41A' as reason, 27 as time from dual union all
2 select 'A', '93K', 16 from dual union all
3 select 'B', '89C', 3 from dual union all
4 select 'B', '93K', 7 from dual union all
5 select 'B', '48C', 4 from dual union all
6 select 'C', '93K', 24 from dual union all
7 select 'C', '93K', 7 from dual union all
8 select 'C', '48C', 10 from dual)
9 --
10 -- END OF TEST DATA TABLE SIMULATED USING 'WITH' CLAUSE
11 -- SIMPLY USE THE SELECT STATEMENT BELOW ON YOUR OWN TABLE
12 --
13 select id
14 ,max(decode(rn,1,reason)) as reason_1
15 ,max(decode(rn,1,time)) as time_1
16 ,max(decode(rn,2,reason)) as reason_2
17 ,max(decode(rn,2,time)) as time_2
18 ,max(decode(rn,3,reason)) as reason_3
19 ,max(decode(rn,3,time)) as time_3
20 ,max(decode(rn,4,reason)) as reason_4
21 ,max(decode(rn,4,time)) as time_4
22 ,max(decode(rn,5,reason)) as reason_5
23 ,max(decode(rn,5,time)) as time_5
24 from (/* assign some row numbers within each ID, ordering by 'reason' then 'time' */
25 select id, reason, time
26 ,row_number() over (partition by id order by reason, time) as rn
27 from t
28 )
29* group by id
SQL> /
I REA TIME_1 REA TIME_2 REA TIME_3 REA TIME_4 REA TIME_5
A 41A 27 93K 16
B 48C 4 89C 3 93K 7
C 48C 10 93K 7 93K 24In this example, it will cater for up to 5 reasons/times per ID... and you can code for more if you need very easily.
Also, as you're using 11g, you can use the new PIVOT query, for which you can find plenty of examples if you google or search these forums, or follow the FAQ link.
If you don't have any idea how many reasons there could be, then you really are looking at generating columns dynamically.
The problem with that is, because Oracle needs to know the SQL projection (see the FAQ link already provided), it has to know how many columns are going to be returned from a query before any data is fetched... but you are saying that the columns returned have to be based on the data itself. To do that you have two main options:
1) You query the data once to determine how many columns you are going to need and then dynamically build up a query in PL/SQL code with the right number of columns (or use one of the other dynamic methods shown in the FAQ)
or
2) You step back and ask yourself if SQL is really the best place to be trying to produce this output. Reporting tools are often better suited to this requirement as they are made to query the data back from a database and then pivot and layout the data based on the data returned.
Maybe you are looking for
-
How do I add my sync items to new phone
Hi all, I recently had a palm centro and did regular syncs to my computer. Yesterday my phone came into contact with my 2 year old and needless to say "it went to heaven", so now I am looking to buy a different palm phone maybe the pixie or maybe jus
-
Compare BEFORE and AFTER image in replicat
Do any of You experts know how to make the following code smaller? ...,p_kolonner=@STRCAT("ID='",@IF(@COLTEST(BEFORE.ID,PRESENT),BEFORE.ID,""),"'>'",@IF(@COLTEST(ID,PRESENT),ID,""),"'¤", "OBSOLETED_ON='",@IF(@COLTEST(BEFORE.OBSOLETED_ON,PRESENT),BEFO
-
Hello, I purchased a 27" dynex for christmas. since day one it had scratchy noise from the left speaker, it was only a few channels at first but slowly progressed until almost all channels were affected. I took it back to BB who sent it off for rep
-
I have added music to my iTunes 7. However, the only problem I have is that the songs are in reverse order. if a cd has 20 songs, it starts the song order from 20-1, instead of 1 - 20. Is there a way I change the way my songs appear. Now that iTunes
-
Adobe Application Modeling Plug-in for LiveCycle ES2
Unable to download this plug-in. Does it require licensing of some sort? Someone please advise. Bliss