Flip rows into column
Hello!
Oracle 9i, NT
I have 2 tables Fact table and Dimension table.
Fact Table has a column called amount. Dimension Table has a column called amount_type which stores the type of amount.
When I write the following SQL statement:
select amount from fact, dimension where fact.key = dimension.key and dimension.amount_type = 'credit' or dimension.amount_type = 'debit';
My results are:
Row 1 : Credit $10
Row 2: Debit $5
What I really want is one row to be returned with credit and debit in that row.
Credit Debit
Row 1: $10 $5
How do I accomplish this? Please help!
Thanks!!!
Hello
Couldn't you just use DECODE to avoid having to rejoin the table.
select
DECODE(d.amount_type, 'Credit',f.amount, NULL) as credit,
DECODE(d.amount_type, 'Debit',f.amount, NULL) as debit
from
fact f,
dim d
where
f.key = d.key
and
d.amount_type IN( 'Credit', 'Debit');Will give you something like
CREDIT DEBIT
100
100
100
100
100
100
100HTH
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 -
Display rows into columns in table
Hi,
I have a table name Ebiz_Upgrade_Task_Status. Here in table there are 8 rows of data with
pro_id,pobj_id,cemli_id and confirmation.
I am trying to convert all the CONFIRMATION into column wise using the query below
SELECT
PRO_ID,
POBJ_ID,
CEMLI_ID,
max(decode(rownum,1,CONFIRMATION,null)) "CP1",
max(decode(rownum,2,CONFIRMATION,null)) "CP2",
max(decode(rownum,3,CONFIRMATION,null)) "CP3",
max(decode(rownum,4,CONFIRMATION,null)) "CP4"
FROM Ebiz_Upgrade_Task_Status
GROUP BY PRO_ID,POBJ_ID,CEMLI_ID
Am able to see first 2 rows of data as columns, and not able to see the next rows. Please suggest me in modifyin the query
tabel strutuce and data
pro_id obj_id cemli_id confirmation
1 2 3 Yes
1 2 3 No
1 2 3 NA
11 22 33 Yes
11 22 33 NO
11 22 33 NA
Please suggest me in modifying the code
Thanks
SudhirThanks for posting more details.
Using rownum caused your confirmation fields to be null:
SQL> select * from temp1;
PRO_ID POBJ_ID CEMLI_ID CONFIRMATION
111 222 333 yes
111 222 333 no
111 222 333 na
11 22 33 na
11 22 33 no
11 22 33 yes
6 rows selected.
SQL> col cp1 format a10
SQL> col cp2 format a10
SQL> col cp3 format a10
SQL> select pro_id
2 , pobj_id
3 , cemli_id
4 , max(decode(rownum,1,confirmation,null)) "cp1"
5 , max(decode(rownum,2,confirmation,null)) "cp2"
6 , max(decode(rownum,3,confirmation,null)) "cp3"
7 from temp1
8 group by pro_id
9 , pobj_id
10 , cemli_id;
PRO_ID POBJ_ID CEMLI_ID cp1 cp2 cp3
11 22 33
111 222 333 yes no na
SQL> select pro_id
2 , pobj_id
3 , cemli_id
4 , max(decode(confirmation, 'yes',confirmation,null)) "cp1"
5 , max(decode(confirmation, 'no',confirmation,null)) "cp2"
6 , max(decode(confirmation, 'na',confirmation,null)) "cp3"
7 from temp1
8 group by pro_id
9 , pobj_id
10 , cemli_id;
PRO_ID POBJ_ID CEMLI_ID cp1 cp2 cp3
11 22 33 yes no na
111 222 333 yes no na
SQL>
Maybe you are looking for
-
Format of numeric field cannot retain via Live Office
In Webi, I changed the format of an numeric field to 2 decimal places. When I retrieved this field to Excel via Live Office, I found the format of 2 decimal places cannot be retained. It ended up displayed in 1 decimal places. I found when a webi r
-
Publish data model with designer
Hi, so far I used ERwin for data modelling. ERwin can generate HTML output consisting of the graphical data model plus hyperlinks on the tables. If you click on a table a report pops up with all details, e.g. table and column comments. I find this ve
-
I have pictures on an external hard drive that are imported into my catalogue. One folder ( out of many) when called up do not show previews when in Libary. If I choose develop, the pictures appears and so does the preview. Whe
-
What is the Safe OC (base clock) for MSI Eplices plus?
Default Base clock for this board is 134. How much can i go still consider as safe OC?
-
Hi, I've a table with contents as follows. Name Salary AD Robert 25000 Md. Amir 22560 Amarnath 23978 Tendulkar 44008 Pele 76890 Punit 21000 How to select only the records with top 3 salaries, i.e Pele,Tendulkar and AD Robert? One way is to sort the r