Rotate Report - Rows into Columns
Hope someone can help me with a SQL script that can turn a report 90 degrees so the row data becomes columns
eg
Select Month, Cost, Discount
from Customer_Table
Month Cost Discount
Jun 08 $34 $6
Jul 08 $47 $3
Aug 08 $87 $8
Should look like this
Month Jun 08 Jul 08 Aug 08
Cost $34 $47 $87
Discount $6 $3 $8
Frank
Rotate Report --> cool title
SQL> with t
2 as
3 (
4 select 'Jun 08' month, 34 cost, 6 discount from dual
5 union all
6 select 'Jul 08', 47, 3 from dual
7 union all
8 select 'Aug 08', 87, 8 from dual
9 )
10 -- end of test data
11 select descr, max(jun_08) jun_08, max(jul_08) jul_08, max(aug_08) aug_08
12 from (
13 select 'cost' descr,
14 decode(month, 'Jun 08', cost) Jun_08,
15 decode(month, 'Jul 08', cost) Jul_08,
16 decode(month, 'Aug 08', cost) Aug_08
17 from t
18 union all
19 select 'discount' descr,
20 decode(month, 'Jun 08', discount) Jun_08,
21 decode(month, 'Jul 08', discount) Jul_08,
22 decode(month, 'Aug 08', discount) Aug_08
23 from t)
24 group by descr
25 /
DESCR JUN_08 JUL_08 AUG_08
cost 34 47 87
discount 6 3 8
SQL>
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 -
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 -
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 -
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> -
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. -
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. -
Hi,
I have a table service_request_master where a column has data like
Srid function_activity_id
1001 12,13,14
1002 11,12
1003 null
1004 19
I need to convert function_activity_ids for each row into columns i.e.
for 1001 it would be 12
13
14
for 1002 11
12
and so on..
I wrote this query but it is not workig for multiple rows:
WITH row_count as (
select length(
ltrim(
rtrim(
translate(function_activity_ids, ',1234567890 ', ',')
) + 1 rc,
',' || function_activity_ids || ',' function_activity_ids
from sop_service_request)
select substr(function_activity_ids,
instr(function_activity_ids, ',', 1, rownum) + 1, -- start_pos
instr(function_activity_ids, ',', 1, rownum + 1) -
instr(function_activity_ids, ',', 1, rownum) - 1 -- data_length
) new_data,
function_activity_ids,
rc
from row_count,
all_tables
where rownum <= rccan you pls help..
a generic function would also do...
Thx,..
JPJP,
I don't know exactly what you want with that null column, but try this:
SQL> create table service_request_master
2 as
3 select 1001 srid, '12,13,14' function_activity_id from dual union all
4 select 1002, '11,12' from dual union all
5 select 1003, null from dual union all
6 select 1004, '19' from dual;
Tabel is aangemaakt.
SQL>
SQL> select srm.srid
2 , case numbers.n
3 when 1 then
4 case instr(srm.function_activity_id,',',1,1)
5 when 0 then srm.function_activity_id
6 else substr(srm.function_activity_id,1,instr(srm.function_activity_id,',',1,1)-1)
7 end
8 else substr
9 ( srm.function_activity_id
10 , 1 + instr(srm.function_activity_id,',',1,numbers.n-1)
11 , case instr(srm.function_activity_id,',',1,numbers.n)
12 when 0 then length(srm.function_activity_id)
13 - instr(srm.function_activity_id,',',1,numbers.n-1) + 1
14 else instr(srm.function_activity_id,',',1,numbers.n)
15 - instr(srm.function_activity_id,',',1,numbers.n-1) - 1
16 end
17 )
18 end single_id
19 from service_request_master srm
20 , ( select level n from dual connect by level <= 3 ) numbers
21 where length(srm.function_activity_id) - length(replace(srm.function_activity_id,',')) + 1
22 >= numbers.n
23 order by srm.srid
24 , single_id
25 /
SRID SINGLE_I
1001 12
1001 13
1001 14
1002 11
1002 12
1004 19
6 rijen zijn geselecteerd.Regards,
Rob. -
How to transpose rows into columns?
How do I transpose all rows into columns like how excel does?
For example:
declare @t table (ProductID int, Type varchar(20), Name varchar(20), isAvailable bit)
insert into @t
select 1, 'Type1', 'Product1',1
union
select 2, 'Type1', 'Product2',0
union
select 3, 'Type2', 'Product3',1
union
select 4, 'Type2', 'Product4',0
Results to:
ProductID Type
Name isAvailable
1 Type1
Product1 1
2 Type1
Product2 0
3 Type2
Product3 1
4 Type2
Product4 0
What I need is:
1
2
3
4
Type1
Type1
Type2
Type2
Product1
Product2
Product3
Product4
1
0
1
0
Where 1,2,3,4 at the top are the columns.select
max(case when Type='Type1' and name ='Product1' then Type end) [1],
max(case when Type='Type1' and name ='Product2' then Type end) [2],
max(case when Type='Type2' and name ='Product3' then Type end) [3],
max(case when Type='Type2' and name ='Product4' then Type end) [4]
from @t
union all
select
max(case when Type='Type1' and name ='Product1' then Name end) [1],
max(case when Type='Type1' and name ='Product2' then Name end) [2],
max(case when Type='Type2' and name ='Product3' then Name end) [3],
max(case when Type='Type2' and name ='Product4' then Name end) [4]
from @t
union all
select
max(case when Type='Type1' and name ='Product1' then cast(isAvailable as varchar(5)) end) [1],
max(case when Type='Type1' and name ='Product2' then cast(isAvailable as varchar(5)) end) [2],
max(case when Type='Type2' and name ='Product3' then cast(isAvailable as varchar(5)) end) [3],
max(case when Type='Type2' and name ='Product4' then cast(isAvailable as varchar(5)) end) [4]
from @t
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 -
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. :) -
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 -
Hi,
create table this_will_be_ugly (column1 number, column2 varchar2(2), column3 number, column4 number);
insert into this_will_be_ugly values (1, 'MA', 100, 10000);
insert into this_will_be_ugly values (2, 'MA', 102, 10001);
insert into this_will_be_ugly values (3, 'MB', 100, 10001);
insert into this_will_be_ugly values (4, 'MC', 200, 10001);
insert into this_will_be_ugly values (5, 'MB', 220, 10003);
insert into this_will_be_ugly values (6, 'MA', 103, 10004);
COMMIT;
CREATE OR REPLACE FUNCTION RET_CROSS_TAN RETURN SYS_REFCURSOR IS
CURSOR CUR_DIST IS SELECT DISTINCT COLUMN2 FROM this_will_be_ugly;
V_SELECT VARCHAR2(30);
V_SELECT1 VARCHAR2(3000);
v_final varchar2(3500);
type ref_cur is ref cursor;
v_ref ref_cur;
BEGIN
OPEN CUR_DIST;
FETCH CUR_DIST INTO V_SELECT;
LOOP
IF CUR_DIST%NOTFOUND THEN
V_SELECT1 := SUBSTR(V_SELECT1,1,LENGTH(V_SELECT1)-1);
EXIT;
END IF;
V_SELECT1 := V_SELECT1||''''||V_SELECT ||''',';
fetch cur_dist into v_select;
END LOOP;
CLOSE CUR_DIST;
v_final := 'WITH PIVOT_DATA AS (select COLUMN2,COLUMN4 AS DATA,COLUMN3 from this_will_be_ugly GROUP BY COLUMN2,COLUMN3,COLUMN4)
SELECT * FROM PIVOT_DATA PIVOT ( MIN(COLUMN3)
FOR COLUMN2 IN ('|| V_SELECT1||'))';
open v_ref for v_final;
return v_ref;
END;
I written this function to form the query which gives the pivot results.
May i know is there any way to write the query directly instead of this function?Hi,
If you want the number of columns in the output to depend on the data in the table, then you have to use dynamic SQL, more or less like you did. The number of columns in a query has to be specified when the query is compiled. You can't compile something today that figures out how many distinct values you will have, and therefore how many columns you will need, tomorrow or next month.
See the following thread for several ways to deal with a dynamic numebr of columns
Re: Report count and sum from many rows into many columns
String aggregation is especially useful.
Maybe you are looking for
-
Text field not showing record set options
I entered the following php code to a text field in a form: <p> <label for="date">Select Available Date</label> <select name="date" class="text" id="date"> <option value="0" selected="selected">select your preferred travel date</o
-
Directory ownership and permissions
After installing WebLogic Server (in /opt/bea as root), I tried to start the admin server and the workSpaceStudio, but both complained about file/directory permissions on various locations under the /opt/bea directory. I started fixing this by openin
-
Send Request to servlet every time with the back button
Hi, We are designing a web site in which all the pages are dynamic depending on what he does with his ordering system. Problem is when the uers request a change to the orders (eg deletes) the page is generated again. But the user can use the back but
-
Why am I given option to "convert selection to aac"?
Help with AAC and my library being added all at once to Itunes I just downloaded Itunes 5.0 for the first time. I am about to purchase an Ipod. Most of my music was downloaded via napster and lots of it is wma protected (not sure if that is relevant
-
How to debug a authority check in program and a authorisation object in tco
Can anyone tell me how to debug a authority check in program and a authorisation object in tcode i just want to know the flow of authorisation object in debugging how user is assocaited with authorisation object and roles. i know if sy-subrc ne 0 is