Pivoting rows into columns in Oracle 10g
Hi,
I want to pivot rows into column in some optimal way.
I don't want to go with the DECODE option as the number of columns can be more than 200.
i have also tried the transpose logic which is making the pl/sql block too huge.
can i directly query the database for the desired output instead of storing the data into some arrays and displaying rows as columns?
Hi,
Here's a dynamic way to do this is Oracle 10, using theSQL*Plus @ command to handle the dynamic parts.
First, let's see how we would do this using a static query:
WITH col_cntr AS
SELECT column_name
FROM all_tab_columns
WHERE owner = 'FKULASH'
AND table_name = 'TEST_EMP'
AND column_name NOT IN ('EMP_ID', 'TYPE_VAL')
, unpivoted_data AS
SELECT e.type_val
, c.column_name
, CASE c.column_name
WHEN 'X_AMT' THEN x_amt -- ***** Dynamic section 1 *****
WHEN 'Y_AMT' THEN y_amt -- ***** Dynamic section 1 *****
WHEN 'Z_AMT' THEN z_amt -- ***** Dynamic section 1 *****
END AS v
FROM test_emp e
CROSS JOIN col_cntr c
SELECT column_name AS type_val
, SUM (CASE WHEN type_val = 'Q1' THEN v ELSE 0 END) AS q1 -- ***** Dynamic section 2 *****
, SUM (CASE WHEN type_val = 'Q2' THEN v ELSE 0 END) AS q2 -- ***** Dynamic section 2 *****
, SUM (CASE WHEN type_val = 'Q3' THEN v ELSE 0 END) AS q3 -- ***** Dynamic section 2 *****
, SUM (CASE WHEN type_val = 'Q4' THEN v ELSE 0 END) AS q4 -- ***** Dynamic section 2 *****
FROM unpivoted_data
GROUP BY column_name
ORDER BY column_name
;Column names are hard-coded in two places:
(1) in the sub-query unpivoted_data, we had to know that there were 3 columns to be unpivoted, and that they were called x_amt, y_amt and z_amt. You want to derive all of that from all_tab_columns.
(2) in the main query, we had to know that there would be 4 pivoted columns in the rsult set, and that they would be called q1, q2, q3 and q4. You want to derive all that from the data actually in test_emp.
Instead of hard-coding those 2 dynamic sections, have Preliminary Queries write them for you, a split second before you run the main query, by running this script:
-- Before writing sub-scripts, turn off features designed for human readers
SET FEEDBACK OFF
SET PAGESIZE 0
PROMPT ***** Preliminary Query 1 *****
SPOOL c:\temp\sub_script_1.sql
SELECT ' WHEN '''
|| column_name
|| ''' THEN '
|| LOWER (column_name) AS txt
FROM all_tab_columns
WHERE owner = 'FKULASH'
AND table_name = 'TEST_EMP'
AND column_name NOT IN ('EMP_ID', 'TYPE_VAL')
ORDER BY column_name
SPOOL OFF
PROMPT ***** Preliminary Query 2 *****
SPOOL c:\temp\sub_script_2.sql
SELECT DISTINCT ', SUM (CASE WHEN type_val = '''
|| type_val
|| ''' THEN v ELSE 0 END) AS '
|| LOWER (type_val) AS txt
FROM test_emp
ORDER BY txt
SPOOL OFF
-- After writing sub-scripts, turn on features designed for human readers
SET FEEDBACK 5
SET PAGESIZE 50
-- Main Query:
WITH col_cntr AS
SELECT column_name
FROM all_tab_columns
WHERE owner = 'FKULASH'
AND table_name = 'TEST_EMP'
AND column_name NOT IN ('EMP_ID', 'TYPE_VAL')
, unpivoted_data AS
SELECT e.type_val
, c.column_name
, CASE c.column_name
@c:\temp\sub_script_1
END AS v
FROM test_emp e
CROSS JOIN col_cntr c
SELECT column_name AS type_val
@c:\temp\sub_script_2
FROM unpivoted_data
GROUP BY column_name
ORDER BY column_name
;As you can see, the main query looks exactly like the static query, except that the two dynamic sections have been replaced by sub-scripts. These 2 sub-scripts are written by 2 prelimiary queries, right before the main query.
As others have said, the fact that you're asking this question hints at a poor table design. Perhaps the table should be permanently stored in a form pretty much like unpivoted_data, above. When you need to display it with columns x_amt, y_amt, ..., then pivot it, using GROUP BY type_col. When you need to display it with columns q1, q2, ..., then pivot it using GROUP BY column_name.
Similar Messages
-
Converting Rows into Column in Oracle 10g
Hi All,
I m using Oracle Version 10.1.0.2.0 - Production
I have requirement to convert rows into column wise as per the following:
My Query is:
WITH t
AS ( SELECT 'A' AS x, 100 AS y FROM DUAL
UNION ALL
SELECT 'B',200 FROM DUAL
SELECT X, Y
FROM t;
X Y
A 100
B 200
My Requirement is
A B
100 200
So any one could help me that how I resolve this.
Regards,
PrasantaDear frank,
Thanks for your support,.
It's working fine for static cases.If the first column is dynamic then how come i will resolve it.
Example:
Create table mytab (ID_C Varchar2(15),Value_N Number);
Records Population into MyTab table is dynamic.
Insert into mytab values('HO',5000);
Insert Into mytab values('PG1',2400);
Insert Into mytab values('PG2',3000);
Insert Into mytab values('PG3',800);
Commit;
SQL> Select * From MyTab;
IDC_ ValueN_
HO 5000
PG1 2400
PG2 3000
PG3 800
Then My expected result will be as follows
HO PG1 PG2 PG3
5000 2400 3000 800
Thanks and Regards,
Prasanta -
Hi all,
I have requirement to display the values in a single column base upon the empid
ex:
select * from emp where empid=1000
then actual result will come as
empid mgr dept sal
1000 10 10 1000
1000 20 20 2000
2000 10 10 1500
2000 20 20 3000but i want the result in the below format
for empid 1000 the result will show as
empid mgr dept sal mgr2 dept2 sal2
1000 10 10 1000 20 20 2000
2000 10 10 1500 20 20 3000Can anyone help me out to achieve this?
Cheers,
Sansomething like this
SQL> ed
Wrote file afiedt.buf
1 with t as
2 (
3 select 1000 empid, 10 mgr, 10 dept, 1000 sal from dual union all
4 select 1000, 20, 20 , 2000 from dual union all
5 select 2000 ,10 , 10 , 1500 from dual union all
6 select 2000 ,20 , 20 ,3000 from dual
7 )
8 select empid,
9 max(decode(mgr,10,mgr)) mgr1,
10 max(decode(mgr,20,mgr)) mgr2,
11 max(decode(dept,10,dept)) dept1,
12 max(decode(dept,20,dept)) dept2,
13 max(decode(mgr,10,sal)) sal1,
14 max(decode(mgr,20,sal)) sal2
15 from t
16* group by empid
SQL> /
EMPID MGR1 MGR2 DEPT1 DEPT2 SAL1 SAL2
1000 10 20 10 20 1000 2000
2000 10 20 10 20 1500 3000 -
Convert rows into columns nad vice versa in 10g
how to convert rows into columns in 10g??
Qwerty wrote:
see below for rows to column case
SQL> WITH t as
2 (
3 SELECT 'US' test_string FROM DUAL UNION
4 SELECT 'AMERICA' FROM DUAL UNION
5 SELECT'HOLLYWOOD' FROM DUAL UNION
6 SELECT 'WASHINGTON' FROM DUAL
7 )
8 select ltrim (sys_connect_by_path(test_string,','),',') test_string
9 from (
10 SELECT row_number() over(order by test_string) rno, test_string
11 FROM t)
12 WHERE connect_by_isleaf = 1 and rownum=1
13 connect by rno = prior rno+1;
TEST_STRING
AMERICA,HOLLYWOOD,US,WASHINGTONI hope you can do it for column to rows now.That's not really rows to columns. That's rows to a column, which is more commonly called string aggregation.
Rows to columns (or pivot) is more like:
SQL> ed
Wrote file afiedt.buf
1 WITH t as
2 (
3 SELECT 'US' test_string FROM DUAL UNION
4 SELECT 'AMERICA' FROM DUAL UNION
5 SELECT'HOLLYWOOD' FROM DUAL UNION
6 SELECT 'WASHINGTON' FROM DUAL
7 )
8 --
9 select max(decode(rn,1,test_string)) as col_1
10 ,max(decode(rn,2,test_string)) as col_2
11 ,max(decode(rn,3,test_string)) as col_3
12 ,max(decode(rn,4,test_string)) as col_4
13* from (select test_string, row_number() over (order by test_string) as rn from t)
SQL> /
COL_1 COL_2 COL_3 COL_4
AMERICA HOLLYWOOD US WASHINGTON
SQL>And columns to rows (or unpivot) is like:
SQL> ed
Wrote file afiedt.buf
1 WITH t as
2 (
3 SELECT 'US' col_1, 'AMERICA' col_2, 'HOLLYWOOD' col_3, 'WASHINGTON' col_4 FROM DUAL
4 )
5 --
6 select col_1 as col from t union all
7 select col_2 from t union all
8 select col_3 from t union all
9* select col_4 from t
SQL> /
COL
US
AMERICA
HOLLYWOOD
WASHINGTONor...
SQL> ed
Wrote file afiedt.buf
1 WITH t as
2 (
3 SELECT 'US' col_1, 'AMERICA' col_2, 'HOLLYWOOD' col_3, 'WASHINGTON' col_4 FROM DUAL
4 )
5 --
6 select decode(rownum,1,col_1,2,col_2,3,col_3,4,col_4) as col
7* from t, (select * from dual connect by rownum <= 4)
SQL> /
COL
US
AMERICA
HOLLYWOOD
WASHINGTON
SQL> -
How to convert row into column
Hi All,
My oracle apps version is r12 and db is 10 and i am using Bi publisher version 10g.
Is it possible to convert row into column in Rtf template,
My Query is
SELECT distinct pvs.vendor_site_code,sum(aia.invoice_amount)
FROM ap_invoices_all aia, po_vendors po, po_vendor_sites_all pvs
WHERE aia.org_id = pvs.org_id
AND aia.vendor_id = po.vendor_id
AND aia.vendor_site_id = pvs.vendor_site_id
AND aia.org_id=204
group by pvs.vendor_site_code
And output is like this
Vendor sitecode Invoiceamt
EAM-ERS 79240
STAR GATE - PAY 3245902.31
UPS - HQ 10792040.9
Like this
So in template i need the output like this
Vendor sitecode EAM-ERS STAR GATE - PAY UPS - HQ
Invoiceamt 79240 3245902.31 10792040.9
I tried to achieve the output using sql query but by hardcoding only i have achieved it, so i have tried to convert directly in RTF template.
can any one tell me is it possible.
And if new project is added from the front end ie(now the query will produce 4 rows but now in template i have created only three columns)
Is it possible to add a new column dynamically.
Can any one please guide me and tell me is there any example.
Thanks & regards
SrikkanthTake a look at this post: http://blogs.oracle.com/roller-ui/bsc/spider.jsp?entry=MT%3aENTRY%3a5001
Thanks,
Bipuser -
Need help with Pivoting rows to columns
Hi,
I need help with pivoting rows to columns. I know there are other posts regarding this, but my requirement is more complex and harder. So, please give me a solution for this.
There are two tables say Table 1 and Table 2.
Table1
name address email identifier
x e g 1
f s d 2
h e n 3
k l b 4
Table2
identifier TRno zno bzid
1 T11 z11 b11
1 T12 z12 b12
1 T13 z13 b13
2 T21 z21 b21
2 T22 z22 b22
As you can see the identifier is the column that we use to map the two tables. The output should be like below
output
name address email identifier TRno1 zno1 bzid1 TRno2 zno2 bzid2 TRno3 zno3 bzid3
x e g 1 T11 z11 b11 T12 z12 b12 T13 z13 b13
f s d 2 T21 z21 b21 t22 z22 b22
Also we do not know exactly how many TRno's, zno's, etc each value in the identifier will have. There may be only 1 TRNO, zno and bzid, or there may be four.
All the values must be in separate columns, and not be just comma delimitted. There are also other conditions that i have to add to restrict the data.
So, can you please tell me what is should use to get the data in the required format? We are using Oracle 10g. Please let me know if u need any more informationSomething like this ?
SCOTT@orcl> ed
Wrote file afiedt.buf
1 select a.name,
2 a.address,
3 a.email,
4 b.* from (
5 select distinct identifier
6 ,max(trno1) trno1
7 ,max(zno1) zno1
8 ,max(bzid1) bzid1
9 ,max(trno2) trno2
10 ,max(zno2) zno2
11 ,max(bzid2) bzid2
12 ,max(trno3) trno3
13 ,max(zno3) zno3
14 ,max(bzid3) bzid3
15 ,max(trno4) trno4
16 ,max(zno4) zno4
17 ,max(bzid4) bzid4
18 from (select identifier
19 ,decode(rn,1,trno,null) trno1
20 ,decode(rn,1,zno,null) zno1
21 ,decode(rn,1,bzid,null) bzid1
22 ,decode(rn,2,trno,null) trno2
23 ,decode(rn,2,zno,null) zno2
24 ,decode(rn,2,bzid,null) bzid2
25 ,decode(rn,3,trno,null) trno3
26 ,decode(rn,3,zno,null) zno3
27 ,decode(rn,3,bzid,null) bzid3
28 ,decode(rn,4,trno,null) trno4
29 ,decode(rn,4,zno,null) zno4
30 ,decode(rn,4,bzid,null) bzid4
31 from (select identifier,
32 trno,bzid,zno,
33 dense_rank() over(partition by identifier order by trno,rownum) rn
34 from table2)
35 order by identifier)
36 group by identifier) b,table1 a
37* where a.identifier=b.identifier
SCOTT@orcl> /
NAME ADDRESS EMAIL IDENTIFIER TRNO1 ZNO1 BZID1 TRNO2 ZNO2 BZID2 TRNO3 ZNO3 BZID3 TRNO4 ZNO4 BZID4
x e g 1 T11 z11 b11 T12 z12 b12 T13 z13 b13
f s d 2 T21 z21 b21 T22 z22 b22
SCOTT@orcl> select * from table1;
NAME ADDRESS EMAIL IDENTIFIER
x e g 1
f s d 2
h e n 3
k l b 4
SCOTT@orcl> select * from table2;
IDENTIFIER TRNO ZNO BZID
1 T11 z11 b11
1 T12 z12 b12
1 T13 z13 b13
2 T21 z21 b21
2 T22 z22 b22
SCOTT@orcl>Regards
Girish Sharma -
Hi,
I am trying to change rows into columns, and I have come up with a package that should do this. However, it doesn't work properly, so am wondering if someone can help me out finding out what is wrong.
I am using the emp table owned by Scott in an Oracle database, and I want my output to look like this:
SAL 10 20 30
800 SMITH
950 JAMES
1100 ADAMS
1250 WARD
1250 MARTIN
1300 MILLER
1500 TURNER
1600 ALLEN
2000
2000 beth
2000 Anne
SAL 10 20 30
2450 CLARK
2850 BLAKE
2975 JONES
3000 SCOTT
3000 FORD
5000 KING
I want the deptno to be the header of the column, except from the first column where I want the salary, and then I want all the employees with the specific salary in the specific department number in the row of the right salary and deptno. I saw on the preview screen that you guys will not see the result like I actually have pasted it in here, but I think you will understand what I want. Out of my result I want to read all the employees in deptno 10,20,30,..... and what the salary is.
So far I have come up with this:
create or replace package pivot
as
type rc is ref cursor;
procedure data(p_cursor in out rc );
end;
create or replace package body pivot
as
procedure data(p_cursor in out rc )
is
l_stmt long;
begin
l_stmt := 'select sal';
for x in ( select distinct deptno from emp order by 1 )
loop
l_stmt := l_stmt ||
', max(decode(deptno,' || x.deptno ||', ename)) "x.deptno"';
end loop;
l_stmt := l_stmt || ' from emp group by sal order by sal';
open p_cursor for l_stmt;
end;
end;
variable x refcursor
set autoprint on
exec pivot.data( :x );
The package gets created without any errors, but when I execute it, it returns the following error:
SQL> exec pivot.data( :x );
BEGIN pivot.data( :x ); END;
ERROR at line 1:
ORA-00936: missing expression
ORA-06512: at "SCOTT.PIVOT", line 14
ORA-06512: at line 1
And I can't see what is wrong with it. Can anyone help?
Thank you.
Regards,
AnneJust like this...and a dbms_output after the open cursor to show you the query begin formed.
create or replace package body pivot
as
procedure data(p_cursor in out rc )
is
l_stmt long;
begin
l_stmt := 'select sal';
for x in ( select distinct deptno from emp order by 1 )
loop
l_stmt := l_stmt ||
', max(decode(deptno,''' || x.deptno ||''', ename)) "'||x.deptno||'"';
end loop;
l_stmt := l_stmt || ' from emp group by sal order by sal';
open p_cursor for l_stmt;
dbms_output.put_line(l_stmt);
end;
end;
Package body created.SQL> set serveroutput on
SQL> exec pivot.data(:x);
select sal, max(decode(deptno,'10', ename)) "10", max(decode(deptno,'20',
ename)) "20", max(decode(deptno,'30', ename)) "30" from emp group by sal order
by sal
PL/SQL procedure successfully completed.
SAL 10 20 30
800 SMITH
950 JAMES
1100 ADAMS
1250 WARD
1300 MILLER
1500 TURNER
1600 ALLEN
2450 CLARK
2850 BLAKE
2975 JONES
3000 SCOTT
SAL 10 20 30
5000 KING
12 rows selected.
SQL>
Think that solves the single quote problem. :) -
Encryptind and decrypting database column in oracle 10g
hi guys...
i am sai sandeep,i got a doubt how to encrypt a database column in oracle 10g..?
i am using a table " emp_uid " ,and strtucture as follows,
create table emp_uid(user_id varchar2(20),pwd varchar2(20));
i need to encrypt a pwd column in the emp_uid.
how to do it..?
thanking u advance.....Ok, here's a basic example...
SQL> create table myusers (username varchar2(30), password varchar2(40));
Table created.
SQL> create or replace procedure add_user(username in varchar2
2 ,password in varchar2) is
3 begin
4 insert into myusers (username, password)
5 values (add_user.username
6 ,dbms_crypto.hash(utl_raw.cast_to_raw(add_user.username||'!'||add_user.password)
7 ,dbms_crypto.hash_sh1)
8 );
9 commit;
10 end;
11 /
Procedure created.
SQL> exec add_user('Fred','Fr3ddy')
PL/SQL procedure successfully completed.
SQL> select * from myusers
2 /
USERNAME PASSWORD
Fred E5C975DB4C0A1CF65683E36421A6305F09F4EA9A
SQL> set serverout on;
SQL> create or replace procedure loginuser(username in varchar2
2 ,password in varchar2) is
3 v_hash varchar2(40);
4 v_username varchar2(30);
5 begin
6 v_hash := dbms_crypto.hash(utl_raw.cast_to_raw(loginuser.username||'!'||loginuser.password), dbms_crypto.hash_sh1);
7 select username
8 into v_username
9 from myusers
10 where username = loginuser.username
11 and password = v_hash;
12 dbms_output.put_line('User: '||v_username||' logged in.');
13 exception
14 when no_data_found then
15 dbms_output.put_line('Username/Password is not valid!');
16 end;
17 /
Procedure created.
SQL> exec loginuser('Fred','Freddy');
Username/Password is not valid!
PL/SQL procedure successfully completed.
SQL> exec loginuser('Fred','Fr3ddy');
User: Fred logged in.
PL/SQL procedure successfully completed.
Ideally you would do the hashing of the password inside the client side application so only the Hashed value goes over the network, but the above demonstrates the principle of using hashes to store passwords. Because it's a one way algorithm, only a brute force method can be used to try and determine the original password. There is no way to directly un-hash the value. To check for a valid login, we don't retrieve the password and try to unhash it to compare against what the user has supplied, we actually take what the user has supplied and hash that in the same way and then compare the hashes.
The point of including the username or some other data in the hashing process means that if two users have the same password, they will still have different hash values, so it won't be apparent they are the same passwords. In my example, the point of putting another character between the concatenation of username and password is in case the username and password together would give the same result e.g.
If we had one user "Fred" with password "Fr3ddy" then just concatenating the strings would give "FredFr3ddy".
If we had another user "FredF" and he happened to choose a password "r3ddy" then just concatenating those would also give "FredFr3ddy"
by introducing a known breaking character they would be different e.g. "Fred!Fr3ddy" and "FredF!r3ddy" and hence give different hash values.
That's the basics of how passwords are stored for security.
It would take a lot of processing power and brute force methods just to determine a single password for a single user when using hashing methods of security.
With encryption, a brute force method could be used to find the decryption key, and once found that could be used to decrypt ALL the encyrpted data, hence it is less secure, especially when some clever person will no doubt have written the key down somewhere so they don't forget it. With hashing there's no key to write down. -
How to convert rows into columns with decode function
Hi,
How to convert rows into columns with the help of decode function in oracle.
thanks and regards
P Prakashsay
col1 col2
1 10
2 20
3 30
then use
select col1,
sum(decode(col2,10,10)) "new1"
sum(decode(col2,20,20))"new2"
sum(decode(col2,30,30))"new3"
from table_name
group by col1;
we used sum u can use ny function if wont u have to give the column name i.e col2 name also
so i think u got it nw
regards -
How to convert rows into column
Hi,
can any one help me how to convert rows into column by pl/sql procedure.
Thanks and Regardshttp://www.oracle.com/technology/oramag/code/tips2004/050304.html
-- dropping the sample table if exists
drop table rowstocol
-- create sample table
create table rowstocol ( name varchar2(20));
-- Inserting rows into sample table
insert into rowstocol values('Amit Zhankar');
insert into rowstocol values('Piyu Yawalkar');
insert into rowstocol values('Piyu Yawalkar');
insert into rowstocol values('Ashish Ghelani');
insert into rowstocol values('Aditi Zhankar');
insert into rowstocol values('Tom Kyte');
insert into rowstocol values('Oracle');
-- Following query should be run to create a sql. This result sql should be run to convert rows to column.
-- The following query uses just the tablename (whose data is to be converted) and name of the column (which is to be converted).
-- Example taken here is table rowstocol, column name.
SELECT cc
FROM (select decode(rn ,1 ,'Select ',null) ||' MAX (CASE WHEN dr = '|| rownum||' THEN DECODE (rn,1, col1) END) '||
decode(rn,maxr,' col1 from ','||'||chr(39)||','||chr(39)||'|| ') cc,rn,maxr
from (SELECT ROWNUM rn,count(0) over() maxr FROM rowstocol) order by rn) trows
union all
select '(SELECT tabs.col1, DENSE_RANK () OVER (ORDER BY col1,rowid) dr,dense_rank() OVER (order by 1) rn
FROM (SELECT NAME col1 FROM rowstocol) tabs ) group by rn' cc from dual;
-- The result of this query will do the reqd conversion from row to column.
-- Replace table rowstocol by your table, column name by your column.
CC
Select MAX (CASE WHEN dr = 1 THEN DECODE (rn,1, col1) END) ||','||
MAX (CASE WHEN dr = 2 THEN DECODE (rn,1, col1) END) ||','||
MAX (CASE WHEN dr = 3 THEN DECODE (rn,1, col1) END) ||','||
MAX (CASE WHEN dr = 4 THEN DECODE (rn,1, col1) END) ||','||
MAX (CASE WHEN dr = 5 THEN DECODE (rn,1, col1) END) ||','||
MAX (CASE WHEN dr = 6 THEN DECODE (rn,1, col1) END) ||','||
MAX (CASE WHEN dr = 7 THEN DECODE (rn,1, col1) END) ||','||
MAX (CASE WHEN dr = 8 THEN DECODE (rn,1, col1) END) col1 from
(SELECT tabs.col1, DENSE_RANK () OVER (ORDER BY col1,rowid) dr,dense_rank() OVER (order by 1) rn
FROM (SELECT NAME col1 FROM rowstocol) tabs ) group by rn
Select MAX (CASE WHEN dr = 1 THEN DECODE (rn,1, col1) END) ||','||
MAX (CASE WHEN dr = 2 THEN DECODE (rn,1, col1) END) ||','||
MAX (CASE WHEN dr = 3 THEN DECODE (rn,1, col1) END) ||','||
MAX (CASE WHEN dr = 4 THEN DECODE (rn,1, col1) END) ||','||
MAX (CASE WHEN dr = 5 THEN DECODE (rn,1, col1) END) ||','||
MAX (CASE WHEN dr = 6 THEN DECODE (rn,1, col1) END) ||','||
MAX (CASE WHEN dr = 7 THEN DECODE (rn,1, col1) END) ||','||
MAX (CASE WHEN dr = 8 THEN DECODE (rn,1, col1) END) col1 from
(SELECT tabs.col1, DENSE_RANK () OVER (ORDER BY col1,rowid) dr,dense_rank() OVER (order by 1) rn
FROM (SELECT NAME col1 FROM rowstocol) tabs ) group by rn;
COL1
Aditi Zhankar,Amit Zhankar,Ashish Ghelani,Oracle,Oracle,Piyu Yawalkar,Piyu Yawalkar,Tom Kyte
Edited by: bhooma on Jan 20, 2009 2:44 AM -
How to convert rows into columns
Hi,
How to convert rows into columns of two different tables.
These two tables have two common columns namely (shipline,pos).
Let me know if we have any built in functions to do this.
thank you very much .
Edited by: 808542 on Dec 7, 2010 8:35 PM
Edited by: 808542 on Dec 7, 2010 8:37 PMHave you tried this first?
http://forums.oracle.com/forums/search.jspa?threadID=&q=row+to+column&objID=f75&dateRange=last90days&userID=&numResults=15&rankBy=10001 -
How to find encrypted columns in oracle 10g database
Hi,
How to find encrypted columns in oracle 10g database? We can see using view dba_encrypted_columns or all_encrypted_columns .
my question is apart from this is there anyother views or tables?
Thanks..user602872 wrote:
Hi,
How to find encrypted columns in oracle 10g database? We can see using view dba_encrypted_columns or all_encrypted_columns .
my question is apart from this is there anyother views or tables?Hmm not which I could find,
SQL> select * from dict where lower(table_name) like '%encrypted%';
TABLE_NAME
COMMENTS
DBA_ENCRYPTED_COLUMNS
Encryption information on columns in the database
ALL_ENCRYPTED_COLUMNS
Encryption information on all accessible columns
USER_ENCRYPTED_COLUMNS
Encryption information on columns of tables owned by the user
SQL>HTH
Aman.... -
I have table having below records.
empno ename deptno
101 a 10
102 b 20
103 c 10
104 d 20
105 e 30
Normal Output using Group by.
deptno count(*)
10 2
20 2
30 1
I want to display like below(rows into columns)
Requiredl Output
10 20 30
2 2 1
Deptnos are in first row and cout of deptno nos are second row.Check out this thread from the FAQ: {message:id=9360005}
-
Coverting a Row into Columns values
Hi SQL Expert Friends,
I have a row which contains 6 columns where I want that data to be shown in the form of columns as shown here:
From:
select item1, item2, item3, amt1, amt2, amt3 from item_table where sno=1; <----- returns 1 row as below
ITEM1 ITEM2 ITEM3 AMT1 AMT2 AMT3
AAA BBB CCC 10.00 20.00 15.00
Data explanation: item1's (AAA) price is amt1 (10.00), item2's (BBB) price is amt2 (20.00) and item3's (CCC) price is amt3 (15.00). OK.
Now I want that data to convert into columns as shown here:
To:
ITEMS AMT
AAA 10.00
BBB 20.00
CCC 30.00
Please help me friends, I want a SQL to display this data.
I found one query which converts a row into columns, but this does not serve my requirement: [for your reference only]
SQL> select substr( the_string
, decode( level, 1, 1, instr(the_string,',',1,level-1)+1)
, decode( instr(the_string,',',1,level), 0, length(the_string), instr(the_string,',',1,level) - decode( level, 1, 0, instr(the_string,',',1,level-1))-1)
) the_value
from ( select (select item1||','||item2||','|| item3 from item_table where sno=1) ITEMS
from DUAL)
connect by level <= length(the_string)-length(replace(the_string,','))+1
Thanks and REgards,
KiranHi, Kirtan,
kiran wrote:
... I want to learn this query, If you could explain me this how it works, then it will definitely helps me.If you don't understand a query that involves sub-queries, make sure you understand the sub-queries first. Run them separately, and study the results.
In this case, the only sub-query is cntr. Run it separately, like this:
WITH cntr AS
SELECT LEVEL AS n
FROM dual
CONNECT BY LEVEL <= 3
SELECT *
FROM cntr;Output:
` N
1
2
3Why did I use the number 3 in "LEVEL <= 3"? Because each row will be unpivoted onto 3 rows. You could make this number 2, or 5, or 25 if that's how many rows you want in the output.
Once you understand the sub-queries, try running the main query. Include the raw values of all columns that play any part in the output. For example:
WITH cntr AS
SELECT LEVEL AS n
FROM dual
CONNECT BY LEVEL <= 3
SELECT CASE cn.n
WHEN 1 THEN co.city1
WHEN 2 THEN co.city2
WHEN 3 THEN co.city3
END AS cities
, CASE cn.n
WHEN 1 THEN co.population1
WHEN 2 THEN co.population2
WHEN 3 THEN co.population3
END AS population
, co.* -- For testing/understanding only
, cn.* -- For testing/understanding only
FROM continent co
CROSS JOIN cntr cn
WHERE co.country = 'America'
;Output:
` POPUL POPUL POPUL POPUL
CITIES ATION COUNTRY CITY1 CITY2 CITY3 ATION1 ATION2 ATION3 N
Phoenix 20000 America Phoenix Los Angeles Chicago 20000 15000 10000 1
Los Angeles 15000 America Phoenix Los Angeles Chicago 20000 15000 10000 2
Chicago 10000 America Phoenix Los Angeles Chicago 20000 15000 10000 3Why are there 3 rows of output? There are 3 rows in the cntr "table", and 3 rows in the continent table. Of these 3 * 3 = 9 rows, only the 3 rows shown above meet the condition in the WHERE clause. (Comment out the WHERE clause and try it again, if you want to see how that works.) Can you see how you get the output (the first 2 columns above) given all the data in the original columns? If not, ask a more specific question about the part you don't understand. -
How can I display the rows into columns.
How can I display the rows into columns. I mean
Create table STYLE_M
(Master varchar2(10), child varchar2(10));
Insert itno style_m
('MASTER1','CHILD1');
Insert itno style_m
('MASTER2','CHILD1');
Insert itno style_m
('MASTER2','CHILD2');
Insert itno style_m
('MASTER3','CHILD1');
Insert itno style_m
('MASTER3','CHILD2');
Insert itno style_m
('MASTER3','CHILD3');
Note : The Master may have any number of childs.
I want to display like this..
Master child1, child2, child3, .......(dynamic)
MASTER1 CHILD1
MASTER2 CHILD1 CHILD2
MASTER3 CHILD1 CHILD2 CHILD3
Sorry for disturbing you. Please hlp me out if you have any slution.
Thanks alot.
Ram DontineniHere's a straight SQL "non-dynamic" approach.
This would be used if you knew the amount of children.
SELECT
master,
MAX(DECODE(r, 1, child, NULL)) || ' ' || MAX(DECODE(r, 2, child, NULL)) || ' ' || MAX(DECODE(r, 3, child, NULL)) children
FROM
SELECT
master,
child,
ROW_NUMBER() OVER(PARTITION BY master ORDER BY child) r
FROM
style_m
GROUP BY
master
MASTER CHILDREN
MASTER1 CHILD1
MASTER2 CHILD1 CHILD2
MASTER3 CHILD1 CHILD2 CHILD3 Since you said that the number of children can vary, I incorporated the same logic into a dynamic query.
SET AUTOPRINT ON
VAR x REFCURSOR
DECLARE
v_sql VARCHAR2(1000) := 'SELECT master, ';
v_group_by VARCHAR2(200) := 'FROM (SELECT master, child, ROW_NUMBER() OVER(PARTITION BY master ORDER BY child) r FROM style_m) GROUP BY master';
v_count PLS_INTEGER;
BEGIN
SELECT
MAX(COUNT(*))
INTO v_count
FROM
style_m
GROUP BY
master;
FOR i IN 1..v_count
LOOP
v_sql := v_sql || 'MAX(DECODE(r, ' || i || ', child, NULL))' || ' || '' '' || ';
END LOOP;
v_sql := RTRIM(v_sql, ' || '' '' ||') ||' children ' || v_group_by;
OPEN :x FOR v_sql;
END;
PL/SQL procedure successfully completed.
MASTER CHILDREN
MASTER1 CHILD1
MASTER2 CHILD1 CHILD2
MASTER3 CHILD1 CHILD2 CHILD3I'll point your other thread to this one.
Maybe you are looking for
-
How to put a few pages together as a panel group in the same screen ?
Dear Friends, Hello. I am developing the accounting application of Journal Entry module. I have developed 5 pages for a journal entry: Journal header, Journal Line, Journal total, Journal Error and Journal Approval. I want to put 5 pages together as
-
How to make the date disappear on the blog summary page?
Hi, I have read thru the message on this forum and can't seem to figure out how to hide or make the date disappear on the blog summary page. I can do it on the blog entry pages by turning the color opacity to 0. I have included my page here:http://
-
Translation Widget Inoperative
For some reason, my stock translation widget just doesnt work anymore. The translation portion of it says "undefined" and has some glitchy looking font written behind the drop-down menu. And the "translate from" either says Chinese (Simplified) or En
-
Error message for OS current update
We have a Mac desktop and are currently running OS X 10.8.3. We received notification of availability for update to received notification for update to 11.0.2. When we attempt to update, we receive an error message which states "an error has occur
-
Data structure similar to database table
i have the need for a data structure that will essentially be the same as a database table. this "table" can be queried against and sorted. currently, i am using an interface to abstract this "table" datastructure, and implementing the interface via