Dynamic query, row to column
Hi.
Is any way to select one row as column for any table exists?
I mean some script which have table name and condition as input parameters, and prints column_name || column value;
I have tried to do it, but have some problems.
e.g. have table
create table my_table (column1 number, column2 number, column3 number);
insert into my_table values (1,2,3);It should be something like:
declare
lv_table_name varchar2(40):='MY_TABLE'; /*these are input paremeters*/
lv_condition varchar2(300):='column1=1;/*these are input paremeters*/
begin
/*body*/
end;and output should be like (may use dbms_output)
column1 1
column2 2
column3 3 Script should work for any table.
Does anybody solves task similar to this?
http://asktom.oracle.com/pls/apex/f?p=100:11:0::::P11_QUESTION_ID:1035431863958
Search for procedure print_table on that page.
Similar Messages
-
dear Friends,
i need query row to column
example
1 a data1 data2 data3
2 b data1 data2 data3
output format
1 2 a
data1 data2 data3Please consider the following when you post a question.
1. New features keep coming in every oracle version so please provide Your Oracle DB Version to get the best possible answer.
You can use the following query and do a copy past of the output.
select * from v$version 2. This forum has a very good Search Feature. Please use that before posting your question. Because for most of the questions
that are asked the answer is already there.
3. We dont know your DB structure or How your Data is. So you need to let us know. The best way would be to give some sample data like this.
I have the following table called sales
with sales
as
select 1 sales_id, 1 prod_id, 1001 inv_num, 120 qty from dual
union all
select 2 sales_id, 1 prod_id, 1002 inv_num, 25 qty from dual
select *
from sales 4. Rather than telling what you want in words its more easier when you give your expected output.
For example in the above sales table, I want to know the total quantity and number of invoice for each product.
The output should look like this
Prod_id sum_qty count_inv
1 145 2 5. When ever you get an error message post the entire error message. With the Error Number, The message and the Line number.
6. Next thing is a very important thing to remember. Please post only well formatted code. Unformatted code is very hard to read.
Your code format gets lost when you post it in the Oracle Forum. So in order to preserve it you need to
use the {noformat}{noformat} tags.
The usage of the tag is like this.
<place your code here>\
7. If you are posting a *Performance Related Question*. Please read
{thread:id=501834} and {thread:id=863295}.
Following those guide will be very helpful.
8. Please keep in mind that this is a public forum. Here No question is URGENT.
So use of words like *URGENT* or *ASAP* (As Soon As Possible) are considered to be rude. -
Dear HTML Gurus,
I have a SQL Query Region that returns/executes a dynamic SQL Query. Based on the number of rows a particular query returns I want to hide or show a different HTML region. I have searched all over for this kind of functionality and have come up with absolutely nothing. I would think that this would be integrated into HTMLDB because Pagination shows the total number of rows returned. Any help or direction would be wonderful.
Thanks,
JamesThis is how I would do it:
1. create an (hidden) item,
2. create a computation for that item and run it after submit. This computation could be a function returning the rowcount value into your (hidden) item - rowcount of my dynamic sql.
If my dynamic query is to big to be entered into the computation "container", which accepts only a limited number of characters, then I would slightly change my approach:
3. I would create a function in my schema and and call this function from the computation level - either through a simple sql query (select function(in parameter) from dual) or, again through a function returning a number.
I tested this and it worked.
Denes Kubicek -
Dynamically convert rows to columns
I've looked at examples on asktom and here and so far everyone I've seen uses decode() or case() but in all cases you have to know the number of columns.. what if you don't?
For example:
select distinct storenbr, pslocation, monthdate, 0 as avg_tran
from aopschedule.staffing_tran_detail, (select last_day(day) monthdate from days
where day between to_date('02/01/2008','mm/dd/yyyy') and to_date('5/31/2008','mm/dd/yyyy'))
where pslocation = '1110'returns
STORENBR PSLOCATION MONTHDATE AVG_TRAN
34806 1110 2/29/2008 0
34806 1110 3/31/2008 0
34806 1110 4/30/2008 0
34806 1110 5/31/2008 0But the date range is dynamic...
So how do I account for this?
I need this to look like
storenbr pslocation feb mar apr may
12345 1234 0 0 0 0
12399 2222 2 1 1 1
...I have Oracle 9i. Thanks
Message was edited by:
GMHi,
As Justin said, the number of columns is fixed when the query is compiled.
Without doing dynamic SQL, you can provide for a worst case. For example, you can write a query that always has columns fro 12 months. If you run the query with parameters such that only three months are needed, the other nine columns will be NULL. This is not especially pretty, but it's relatively easy.
You can do a truly dynamic querry In SQL*Plus. Instead of hard-coding a query such as
SELECT storenbr
, pslocation
, SUM (DECODE (n, 1, cnt)) AS col_1
, SUM (DECODE (n, 2, cnt)) AS col_2
FROM staffing_tran_detail
you can put the text shown in bold above (whether it's two columns, as in the example above, or three, or twelve) into a substitution variable. To define that substitution varibale dyamically, use the SQL*Plus "COLUMN ... NEW_VALUE" command, and run a preliminary query (which can be in the same script) to define the variable. If this involves concatenating multiple short rows of output into one very long row, there are a number of string aggregation techiques, such as the user-defined STRAGG function.
Like Justin said, this is not trivial. If you're serious about doing it, post as much code as you can (such as a query with three hard-coded columns), and ask for help with the next step. -
Transposing of queried rows into columns
Hi, i have a query that produces an output of several rows (i.e. no. of days in a month). How do I modify my query so that instead of getting 31 rows for january, I will have one row with 31 columns or values? Thank you.
Thank you very much for your response. You definitely got what i wanted to do but honestly, I'm having a hard time applying this to my query since I am not very familiar with the WITH AS, CONNECT BY LEVEL and the PRIOR commands, coupled with the fact that I have to produce my output ASAP. I have this query:
SELECT A.PLTCODE, A.PLTACTLGEN, A.INPTDATE
FROM PMC_ACTLGEN A
WHERE A.INPTDATE >
TO_DATE ('10/31/2013 00:00:00', 'MM/DD/YYYY HH24:MI:SS')
AND A.INPTDATE <
TO_DATE ('01/01/2014 00:00:00', 'MM/DD/YYYY HH24:MI:SS')
ORDER BY --
A.PLTCODE, A.INPTDATE
which produce an output that looks like this:
PLTCODE
PLTACTLGEN
INPTDATE
AMB
0
11/1/2013
AMB
204
11/2/2013
AMB
107
11/3/2013
AMB
968
11/4/2013
AMB
1379
11/5/2013
AMB
1493
11/6/2013
AMB
1457
11/7/2013
AMB
1099
11/8/2013
AMB
1893
11/9/2013
AMB
2517
11/10/2013
AMB
2521
11/11/2013
AMB
2448
11/12/2013
AMB
701
11/13/2013
AMB
1785
11/14/2013
AMB
2002
11/15/2013
AMB
1601
11/16/2013
AMB
1225
11/17/2013
AMB
1572
11/18/2013
AMB
1579
11/19/2013
AMB
1576
11/20/2013
AMB
1722
11/21/2013
AMB
1610
11/22/2013
AMB
175
11/23/2013
AMB
813
11/24/2013
AMB
1674
11/25/2013
AMB
2198
11/26/2013
AMB
1841
11/27/2013
AMB
1970
11/28/2013
AMB
1918
11/29/2013
AMB
721
11/30/2013
How do I exactly modify this query to produce an output such that the INPTDATE is arranged as columns e.g.
INPTDATE 1 2 3 4 5 6 7 . . . 30
AMB 0 204 107 968 1379 1493 1457 . . . 721
PLEASE HELP! Thanks a lot! -
Dynamic populate rows and columns in adf table
Hi everybody !
I have a query thats returns a unic value !
and I want to populate an af:table with this value !
i need to execute this query to get the values for each columns .... and jump to next row and continue to execute the query for new values of the columns of the new row !!!
in backing bean ... im try to do someting like this :
RichColumn coluna = new RichColumn();
coluna.setId("id");
HtmlOutputText out = new HtmlOutputText();
out.setId("receive");
out.setValue("Contas a Receber");
coluna.getChildren().add(out);
out = new HtmlOutputText();
out.setId("pay");
out.setValue("Contas a Pagar");
coluna.getChildren().add(out);
this.getTableFluxo().getChildren().add(coluna);
but i get the same values for all the rows !!!!Hi there,
If you use ADF BC you can make transient variable in the View Object and fill it in the get method,every time the
get method is executed you will execute the query and change the value of the new transient variable.
Even better solutions is to extend the query with this extra column and map the table with it.
Regards,
Alexander -
Oracle 10g query rows to column transpose
In oracle 10g I have table called LoginUser
Select * from LoginUser where Day = '01-Dec-2012'
will give me the below result
Day, Name, Country
1-Dec-12 , John, UK
1-Dec12 , Cate, US
1-Dec-12 , Prakash, India
1-Dec-12 ,Juli, Pak
But I want result as below
Day, Name1, Country1, Name2, Country2, Name3, Country3, Name4, Country4
1-Dec-12, John, UK, Cate, US, Prakash, India, Juli, Pak
Please help
Edited by: 975340 on Dec 6, 2012 1:48 AM
Edited by: 975340 on Dec 6, 2012 1:50 AMRefer to below thread
Re: Multiple rows into a single line in 'Single Column Table' -
I have a table something like
WHERE IN
Age 18
Year 2012,2013
Color Blue
--etc
I would like to create a dynamic statement base on this table
Dyanmic SQL:
WHERE AGE IN (18) and Year IN (2012,2013) and Color IN (‘Blue’)
I am using SQL server 2008 R2. How can I do this using XML path or somethingHere you go:
DECLARE @tbl TABLE ([WHERE] sysname NOT NULL,
[IN] nvarchar(200))
INSERT @tbl([WHERE], [IN])
VALUES ('Age', '18'), ('Year', '2012,2013'), ('Colour', 'Blue,Yellow')
DECLARE @where nvarchar(MAX)
SELECT @where =
(SELECT [WHERE] + ' IN (' +
CASE WHEN [IN] LIKE '%[^0-9,]%'
THEN replace(quotename([IN], ''''), ',', ''',''')
ELSE [IN]
END + ') AND '
FROM @tbl
FOR XML PATH(''), TYPE).value('.', 'nvarchar(MAX)') + ' 1 = 1'
SELECT @where
However, this is somewhat brittle. I'm assuming that a comma is a list separator; never part of a value searched for. I'm also assume that as long as a value is digits only, it is numeric, else it is a string. This would fail if there is a date value
on the form YYYYMMDD.
Probably you should store metadata somwhere, so that you know the data type of a column.
Erland Sommarskog, SQL Server MVP, [email protected] -
Hello All,,
There used to be an option in Hyperion planning 11.1.1.3 to Dynamic add rows in data form. I don't see this option in planning 11.1.2.1 ?
Could you please suggest how we can grant right users to add dynamic add rows and columns in data forms? or it is possible in 11.1.2.1 ?
out user want to have a feature of adding row in data forms (planning forms)
Thank you
Edited by: 842804 on Aug 17, 2011 12:49 PMDo you mean 11.1.2, if so then adhoc web forms really take over from adding rows as they add much more functionality.
Cheers
John
http://john-goodwin.blogspot.com/ -
Hello All,,
There used to be an option in Hyperion planning 11.1.1.3 to Dynamic add rows in data form. I dont see this option in planning 11.1.1.2 ?
Could you please suggest how we can grant right users to add dynamic add rows and columns? or it is possible in 11.1.1.2
Thank youHow about ad-hoc analysis? Have a read of this: http://download.oracle.com/docs/cd/E17236_01/epm.1112/hp_user/ch04s02s03.html
Cheers,
Mehmet -
Converting rows to columns using dynamic query.
I am trying to use the below code that I founnd on the web to conver rows to columns. the reason that I want to use dynamic query is that the number of rows are not know and changes.
declare
lv_sql varchar2(32767) := null ;
begin
lv_sql := 'SELECT Iplineno ';
for lv_rec in (SELECT distinct vendor from bidtabs where letting = '10021200' and call ='021')
loop
lv_sql := lv_sql
|| CHR(10)
|| ', MAX( DECODE( vendor, '
|| chr(39)
|| lv_rec.vendor
|| CHR(39)
|| ', bidprice, NULL ) ) as "'
|| lv_rec.vendor
|| '" ' ;
end loop;
lv_sql := lv_sql
|| CHR(10)
|| 'FROM bidtabs where letting = ''10021200'' and call = ''021'' and lineflag = ''L'' '
|| CHR(10)
|| 'GROUP BY iplineno ;' ;
here is the result
BIDPRICE CALL IPLINENO LETTING VENDOR
9,585 021 0010 10021200 C0104
1,000 021 0020 10021200 C0104
1,000 021 0030 10021200 C0104
17 021 0040 10021200 C0104
5 021 0050 10021200 C0104
11,420 021 0010 10021200 K0054
1,100 021 0020 10021200 K0054
1,100 021 0030 10021200 K0054
5 021 0040 10021200 K0054
3 021 0050 10021200 K0054
8,010 021 0010 10021200 V070
900 021 0020 10021200 V070
1,320 021 0030 10021200 V070
11 021 0040 10021200 V070
3 021 0050 10021200 V070
and here is the desired output
CALL IPLINENO LETTING C0104 K0054 V070
021 0010 10021200 9,585 11,420 8,010
021 0020 10021200 1,000 1,100 900
021 0030 10021200 1,000 1,100 1,320
021 0040 10021200 17 5 11
021 0050 10021200 5 3 3Here is the error message I am getting:
RA-06550: line 22, column 43:
PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following:
begin case declare end exception exit for goto if loop mod
null pragma raise return select update while with
<an identifier> <a double-quoted delimited-identifier>
<a bind variable> << close current delete fetch lock insert
open rollback savepoint set sql execute commit forall merge
pipe -
How to accessing current row report column value in Lov Query?
Hi,
which access methods (eg. bind variables, substitutions, ...) for getting the current row report column value can be used in the "Lov Query" property of a report column?
As what I know of and what I have read on the forum there are no bind variables for the report columns. For the "Link Text" property it seems that the column values exist as substitution strings (#COLUMN_NAME#). But they don't work in the Lov Query. => And would be good because of a hard parse each time the Lov query is executed.
The following post (Re: Simulating a correlated sub query in lov
is showing a solution to use package variables for temporary storage of the referenced value, but the only problem with that solution is that if a new record is added with the "Add rows to tabular form" process the package variable still contains the value from the last queried row! Is there a way (variable, APEX package, ...) to determine if the lov query is executed for a new record so that the package can return null?
I know that I could write the package in a way that the value is immediately cleared when lov_pkg.keyval is called (one time read), but then I would have to create several variables if I'm accessing the value multiple times in the query or in another query => I think an one time read solution would be very obscurely.
Thanks for your help
Patrick
http://inside-apex.blogspot.comHi Patrick,
I agree that it's a waste to continually use Ajax to go back to the server to get the contents of a dynamic select list.
There are no bind variables for any row item - but what you do have, as per my previous post, is the value of the data entered by the user in the first row. You can pass this into your application process (using get.add("VARIABLENAME", value)), which can use it to retrieve the correct LOV in your Ajax code - this will give you a "bind variable" that your process can use.
What you could do, however, is generate hidden select lists on your page - one for each possible LOV list and replace the contents of the new row's select list with the contents of the appropriate hidden select list. This is easy to do with javascript (using innerHTML functions). Obviously, though, the usefulness of this depends on the number and size of the select lists.
Even if you don't generate them to start with, you can keep a copy of any select lists returned by Ajax in the DOM for use on new rows. So, if you have retrieved a select list, you will have a copy of it in DOM which you can then copy into the new row. If you don't have the list in DOM, use Ajax to get it, store a copy of it and copy it into the new row.
Which method you use will depend on the number/size of select lists needed. If they are few in number and/or size, I would suggest generating hidden lists. If they are large, use Ajax to get them once, store them and then retrieve them from the DOM when needed.
There is another thread here where Arie recommends going to the server every time to make sure you get the most up-to-date data for the lists. If you want to follow this advice, for this reason, use get.add("VARIABLENAME", value) to pass the value to your process. If this is not an issue, you can use one of the other methods I outlined above.
Regards
Andy -
Cursor in select query in row to column format
Hi
I have the query like below
SELECT d.department_id,
CURSOR(SELECT e.first_name,
e.last_name
FROM employees e
WHERE e.department_id = d.department_id
) emps
FROM depatments dI want the result set in a format of Row To columns like
10 20
<cursor result> <cursor result>pls give ur suggestions how to achieve this in a efficient way?I tried the method of "max(decode(.." but dont think so its possible with thisvishnu prakash wrote:
Hi
I have the query like below
SELECT d.department_id,
CURSOR(SELECT e.first_name,
e.last_name
FROM employees e
WHERE e.department_id = d.department_id
) emps
FROM depatments dI want the result set in a format of Row To columns like
10 20
<cursor result> <cursor result>pls give ur suggestions how to achieve this in a efficient way?I tried the method of "max(decode(.." but dont think so its possible with thisNumber of column of a select query is static. Must be known at the parsing time itself. But in your case i dont think the number of columns will be limited to 2 (10 and 20) there could be many more.
You can search this forum to see how to PIVOT your data. There are lot of example. You can also try dynamic pivot. Its all in here, just search. -
Dynamic SQL Pivoting(Converting Row to Columns)
Hi All,
I am using Oracle 9i (Oracle9i Enterprise Edition Release 9.2.0.1.0 - Production)
and also 10g version
I am facing difficulties to find out the logic for
converting the set of values in one of the columns into the column headings for the entire query.
create TABLE my_tab ( deptno VARCHAR2(5), job VARCHAR2(50), sal NUMBER);
insert into my_tab ( deptno,JOB, sal) values ( 10, 'ANALYST', 23000);
insert into my_tab ( deptno,JOB, sal) values ( 10, 'SALESMAN', 1500);
insert into my_tab ( deptno,JOB, sal) values ( 10, 'CLERK', 3550);
insert into my_tab ( deptno,JOB, sal) values ( 20, 'SALESMAN', 700);
insert into my_tab ( deptno,JOB, sal) values ( 20, 'ANALYST', 4200);
insert into my_tab ( deptno,JOB, sal) values ( 30, 'SALESMAN', 5600);
insert into my_tab ( deptno,JOB, sal) values ( 30, 'CLERK', 12000);
insert into my_tab ( deptno,JOB, sal) values ( 30, 'ANALYST', 19000);
COMMIT;
SELECT * FROM my_tab
DEPTNO ______ JOB ________ SAL
10 ______ ANALYST ________ 23000
10 ______ SALESMAN ________ 1500
10 _______ CLERK ________ 3550
20 _______ SALESMAN ________ 700
20 _______ ANALYST ________ 4200
30 _______ SALESMAN ________ 5600
30 _______ CLERK _______ 12000
30 _______ ANALYST _______ 19000
--And I wish to convert it into this structure:
DEPTNO ________ ANALYST ________ SALESMAN _________ CLERK
10 ________ 23000 ________ 1500 _________ 3550
20 ________ 4200 ________ 700 _________ NULL
30 ________ 19000 ________ 5600 _________ 12000
It may be dynamic. i.e Later i inserted more two records into My_tab.
insert into my_tab ( deptno,JOB, sal) values ( 20, 'CLERK', 3400);
insert into my_tab ( deptno,JOB, sal) values ( 30, 'MANAGER', 48000);
So it should be dynamic.
output is like this.
DEPTNO ________ ANALYST ______ SALESMAN ______ CLERK ______ MANAMGER
10 ________ 23000 ______ 1500 ______ 3550 ______ NULL
20 ________ 4200 ______ 700 ______ 3400 ______ NULL
30 ________ 19000 ______ 5600 ______ 12000 ______ 48000
Please help me regarding this.
With warm regards,
PrasantaHi, Prasanta,
Displaying one column from many rows as many columns on one row is called Pivoting . The following thread shows the basics of how to pivot:
Help for a query to add columns
That example uses the aggregate COUNT function; you'll want SUM (or possibly MIN or MAX) instead.
Getting a dynamic number of columns requires Dynamic SQL . As a simpler alternative to pivoting and dynamic SQL, you might consider String Aggregation , where you concatenate a column from many rows into one big string, to be displayed on one row.
See the following thread for more about string aggregation and other options on pivoting into a variable number of columns:
Re: Report count and sum from many rows into many columns -
Need query to convert Single Row Multiple Columns To Multiple rows
Hi,
I have a table with single row like below
Column0 | Column1 | Column2 | Column3 | Column4|
Value0 | Value1 | Value2 | Value3 | Value4 |
Am looking for a query to convert above table data to multiple rows having column name and its value in each row as shown below
Column0 | Value0
Column1 | Value1
Column2 | Value2
Column3 | Value3
Column4 | Value4
Thanks in advance.
MohanHi ykMohan,
Dynamic UNPIVOT can be applied in this case as well.
CREATE TABLE dbo.T(ID INT,Column0 VARCHAR(99),Column1 VARCHAR(99),Column2 VARCHAR(99),Column3 VARCHAR(99),Column4 VARCHAR(99))
INSERT INTO T VALUES
(1,'Value0','Value1','Value2','Value3','Value4'),
(2,'Value0','Value1','Value2','Value3','Value4');
DECLARE @columns VARCHAR(MAX)
SELECT @columns=
STUFF(
SELECT ','+ COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='T' AND TABLE_SCHEMA='dbo' AND Column_name NOT IN('ID') FOR XML PATH('')
),1,1,'')
DECLARE @Sql NVARCHAR(MAX)
SET @Sql =
'SELECT ID, UPT.col,UPT.val FROM T
UNPIVOT
(val FOR col IN('+@columns+')) AS UPT'
EXEC sp_executeSQL @Sql
DROP TABLE T
If you have any feedback on our support, you can click
here.
Eric Zhang
TechNet Community Support
Maybe you are looking for
-
Can we upload more than one document at a time ?
It will take me forever to upload all my documents into the acrobat cloud , ONE at a time....is there a quicker way to do it? If not, will there be soon? Because that would really help me and possibly others to get it done faster...
-
Trying to create a page region that has the following characteristics. Does HTMLDB have a pre-built component to do the following? I tried the List Manager component, but that doesn't seem right for this. I think the missing piece I need is the javas
-
Improving Search for Keywords in NI Example Finder
Search for Keywords is presently limited to logical "OR" search. It would highly profit from logical "AND" Search.
-
New computer need to download ps elements 9
how do I download the elements 9 onto my new computer?
-
I know a little English I bought 14000gems in the warriors2 =エターニティーウオー. Shop on Saturday But there write 3000free,altogether 6000, I'm not receive just receive 14000 these is what situation My apple Id is. [email protected] Please help me