Convert data in rows to columns
Hi,
my table structure in this
Emp_id loancode interest principal
1 003 12 1000
1 004 12 2000
2 007 16 2500The same employee might have take two different loans.i need to display each loan detail as a separate column...like
Empi_id soc_code loancode003 interestforloancode003 principal_for_loancode003 loancode004 i
int_004 principal_for_loancode004i need to break on every different emp_id and soc_code(from another table)
pls help out
Regards,
bhooma wrote:
1 create table dta as
2 select 'Jan' as period, 2000 as op_bal, 3000 as cl_bal from dual union all
3 select 'Feb', 3000, 3000 from dual union all
4 select 'Mar', 2500, 2000 from dual union all
5* select 'Apr', 3000, 3250 from dual
SQL> /
Table created.
SQL> select * from dta;
PER OP_BAL CL_BAL
Jan 2000 3000
Feb 3000 3000
Mar 2500 2000
Apr 3000 3250
SQL> ed
Wrote file afiedt.buf
1 select decode(rn,1,'Op/Bal','Cl/Bal') as type
2 ,max(decode(period, 'Jan', decode(rn,1,op_bal,cl_bal))) as Jan
3 ,max(decode(period, 'Feb', decode(rn,1,op_bal,cl_bal))) as Feb
4 ,max(decode(period, 'Mar', decode(rn,1,op_bal,cl_bal))) as Mar
5 ,max(decode(period, 'Apr', decode(rn,1,op_bal,cl_bal))) as Apr
6 from dta, (select rownum as rn from dual connect by rownum <= 2) x
7* group by rn
SQL> /
TYPE JAN FEB MAR APR
Op/Bal 2000 3000 2500 3000
Cl/Bal 3000 3000 2000 3250
SQL>If you're going to steal my example from the other thread, at least credit me with it and post it properly formatted with {noformat}{noformat} tags. Better still, if you know of working examples on other threads, just link to that thread so the original poster here can see the context in which the answer is given.
Similar Messages
-
How to convert data from rows into columns
Hi,
I have a sql table and the data looks like this
GLYEAR GLMN01 GLMN02 GLMN03 GLMN04
2007 -109712.40 6909.15 4758.72 56.88
2007 -13411.32 19132.9 -5585.07 4362.64
Where GLyear reprsents Year and GLMN01 is February, GLMN02 is March and so on,
Now i want my output to be something like this which i want to insert into another table
GLYear GLMonth GLAmount
2007 February -109712.40
2007 March 6909.15
2007 April 56.88
My new table has 3 columns, GLYear,GLMonth,GLAmount.
Can someone please help me with the select statement on how to do this, i can work with the inserts.
Thanks.I want you to check these form tread they have the same discussion as you. They will definitely solve your problem
http://blog.jontav.com/post/8344518585/convert-rows-to-columns-columns-to-rows-in-sql-server
http://dba.stackexchange.com/questions/19057/convert-rows-to-columns-using-pivot-in-sql-server-when-columns-are-string-data
http://stackoverflow.com/questions/18612326/how-to-convert-multiple-row-data-into-column-data-in-sql-server
I hope this helps you in solving your problem.
Please remember to click “Mark as Answer” on the post that has answered your question as it is very relevant to other community members dealing with same problem in seeking the right answer -
How to transpose the data records (rows) to column(lists) using apd
Hi,
how to transpose the data records (rows) to column (lists) using apd in sap bw.
I do not want to use abap routine.only use the transpose rows to list transformation .
Pls provide the step by step procedure .
thanks,
NimaiSave youe file to transpose as a csv and in the header row of your file for the columns you want to transpose you need to put some soer of a tag before the column name (ie your colum header was for a period budget will be something lie 2011001:ZFIBDD)
1. You will need to create a new apd process (rsanwb)
2. Insert a "Read from Data File" data source object and map it file (,csv)
3. insert a transpose object into your apd process (middle row 4th one over in the transformations section)
4. under the definition tab in the transformation object select all the columns that are to be transposed into rows and move them to the transformed area, the grouping fields section should contain the rows that you want to now be columns
5.under the transformation tab enter in the seperator you selected under the Field Name/Infoobject area (ie. ZFIBDD)
6. under the details tab you need to enter in all the fields to be transformed and tner the transposition field (ie ZFIBDD)
7. Then you can insert a set of transformations and a DSO and link the newly transposed fields into that.
hope that helps -
How to convert a table data from rows to columns?
Hi,
I have a Employee table of the following format:
Emp_id | Emp_name | Salary
101 | James | 1000
102 | Julia | 2000
I have to convert or transpose the table data as follows using a SQL statement/function -
Emp_id | 101 | 102
Emp_name | James | Julia
Salary | 1000 | 2000
How do I achieve this?
Please help me.
Thanks,
993012
Edited by: 993012 on Mar 11, 2013 3:26 AM993012 wrote:
Hi Pavan,
Thanks for the prompt reply.
The link seems to be of not relevant to my question.
My question is to clearly transpose the rows to columns and vice versa without any changes to data.
Regards,
993012I do not see any modification to the data in the Link posted by Pavan. Anyways, One catch with Transposing the Rows is, you need to know the Number of Columns you need to project.
With Static SQL, there is no way to do so. Hence, you will need PL/SQL with Execute Immediate/Dynamic SQL.
See demostration by Tom Kyte on Dynamic Pivots to have a look at the example and adapt to your situation.
Although, I will debate on the need to do it in SQL. Because what you are upto is a part of Reporting and there are many reporting Tools which will have this functionality in-built. SQL, ideally should not be used for reporting purposes. It sole purpose it to store and pass the data to be rendered by Client Software i.e. Java or Third Party tools. -
Exporting data in rows and columns and loading in RDBMS
<p>I have a scenario wherein i want to export data from HyperionEssbase in <b>rows and coulmns</b> and <b>load it into</b><b>RDBMS</b>. I can load data into RDBMS using informatica if theflat file exported is in form of rows and columns.But when i exportthe file using Hyperion Essbase 9 i get it in from of alldimensions and then the fact value which is not how i want. I wantdata in relational from in flat file itself(row,column).</p><p>Looking forard to your suggestions..Thanks in advance..</p>
<p>Thanks <b>willjordan</b> and <b>twakim</b> for yoursuggestions..</p><p> </p><p>I tried both the techniques and both worked...</p><p>With reference to the technique suggested by <b>twakim</b> , I was able to use that in Hyperion Essbase 9..But in myreal scenario the cube is in Hyperion Essbase 6.5.4.2..Can i usethis Custom defined functions in Hyperion Essbase 6.5.4.2..and ifso how as there is no concept of Analytical server there???</p><p> </p><p>Please help me in this issue???<br></p>
-
Transposing Table Data From Rows to Columns Into a View
I have a web-based HRMS (Human Resources Management System) ERP with a back-end SQL Server 2008 R2. I'm trying to compare the actual manpower with the manpower contract requirements for 30 cost centers. My base data is as follows:
TABLE Contract_Requirements: Class, Cost_Center, Contract_Qty
VIEW Manpower_Count: Class, Cost_Center, Head_Count
I would like to transpose the rows to columns of both objects so that the end result would be similar to the following:
Class | Site_1 |
Site_2 | Site_3 | Site_4
|...
Superintendent 1
1 1
1
Supervisor 2
2 2
2
Medic 1
2 1
3
Crane Operator 1
1 2
1
The target layout is that each individual record displays the number of employees of a specific class allocated to each individual cost center; the cost centers become columns. I was able to accomplish this using the following TSQL:
DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX)
SELECT @cols = STUFF((SELECT ',' + QUOTENAME(Cost_Center)
FROM Manpower_Count
GROUP BY Cost_Center
ORDER BY Cost_Center
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)'),1,1,'')
SET @query = 'SELECT Class,' + @cols + ' INTO
Manpower_Allocation_Matrix FROM
(SELECT Class, Cost_Center, Head_Count
FROM Manpower_Count) x
PIVOT (SUM(Head_Count) FOR Cost_Center IN (' + @cols + '))p'
EXECUTE(@query);
The only problem is if an employee is transferred from one cost center to another, which happens a lot on a daily basis, this would only be reflected in the base view; the resultant table will not be updated. I would have to repeatedly drop and recreate
the table which isn't efficient, nor is it the right practice. I was thinking of automating this using a scheduled procedure every day, but it's still not going to work. The actual manpower count must be known at real-time, meaning any changes should be reflected
immediately after any employee transfer. What is the most efficient way to automate this process and store real-time data? FYI, I'm not an SQL expert and have never worked with
stored procedures or triggers. I would also like to point out the number of cost centers is never fixed; consequently the number of columns aren't fixed either.Hi Seif,
You can pivot straightly on the base view to get real time data. The dynamic PIVOT is encapsuled in a Stored Procedure(SP), so every time your want to check the manpower count you can call the SP.
--This table is the same with your base view
CREATE TABLE srcTbl(
Employee_Code VARCHAR(99),
Employee_Name VARCHAR(99),
Cost_Center_name VARCHAR(99),
Cost_Center_NO VARCHAR(99),
Position_ VARCHAR(99),
Total_Salary Money
INSERT INTO srcTbl VALUES('CAN-010','John Doe A','Site 120',120,'Fork Lift Operator',150);
INSERT INTO srcTbl VALUES('EGY-130','John Doe B','Site 150',150,'Driver',200);
INSERT INTO srcTbl VALUES('IND-120','John Doe C','Site 113',113,'Fork Lift Operator',150);
INSERT INTO srcTbl VALUES('SAU-50','John Doe D','Site 112',112,'Mechanic',261.948);
INSERT INTO srcTbl VALUES('PHI-90','John Doe F','Site 112',112,'Crane Operator',250);
INSERT INTO srcTbl VALUES('CAN-012','John Doe G','Site 120',120,'Driver',200);
INSERT INTO srcTbl VALUES('IND-129','John Doe I','Site 150',150,'Superintendent',2300);
INSERT INTO srcTbl VALUES('PAK-464','John Doe X','Site 141',141,'Supervisor',1800);
INSERT INTO srcTbl VALUES('FRA-003','John Doe M','Site 120',120,'Medic',700);
GO
CREATE PROC proc1
AS
DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX)
SELECT @cols = STUFF((SELECT ',' + QUOTENAME(Cost_Center_no)
FROM srcTbl
GROUP BY Cost_Center_no
ORDER BY Cost_Center_no
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')
SET @query=N';WITH Cte AS(
SELECT Position_ as Class,Cost_Center_No, COUNT(1) AS Head_Count FROM srcTbl
GROUP BY Position_,Cost_Center_No
SELECT Class,'+@cols+'
FROM Cte
PIVOT
(MAX(Head_Count) FOR Cost_Center_No IN('+@cols+')) AS PvtTbl
ORDER BY Class';
EXEC sp_executesql @query ;
GO
EXEC PROC1
DROP PROC PROC1
DROP TABLE srcTbl
If you have any question, feel free to let me know.
Eric Zhang
TechNet Community Support -
Dates against rows and columns in pivot require two date dimensions???
Hi,
I have an Excel pivot table connected to a SSAS tabular cube.Now For this Report i want the row label area of pivot to contain Shipping Month and column label area contains the Order Months.Do i need two date dimensions for this purpose?? What is the way
to do such kinds of Reports where the row as well as columns contain date dimension???
Thanks.Hi Nimo0102,
Based on your description, you want Shipping Month to be shown on row label, and Order Months to be shown on the column label, right? When connecting to a data base on an Excel pivot table, if we want to the dimension appear on the row or column label, we
can drag the dimension to ROWS or COLUMNS. So in your scenario, if you have Shipping Month Order Months on your cube, you can drag it to ROWS or COLUMNS directly. Otherwise, I am afraid you need to create them on the cube.
If I have anything misunderstood, please point it out.
Regards,
Charlie Liao
TechNet Community Support -
How to convert Date,month,date range row to column
hi experts
i have a requirement like
i want to change date, month and if user key in date range (01-04-2010 to 31-04-2010) then o/p like below
1st-o/p-format
d1 d2 d31
01-04-2010 02-04-2010 ------------------------------- 31-04-2010
2nd-o/p-format -based on transaction month
d1 d2 d31
jan feb ------------------------------------------ mar
3rd-o/p-format date range based on transaction date
d1 d2 d31
01-04-2008 02-04-2010 -------------------------------31-04-2009
Note :Basically i want to display these formate in Oracle Forms then based these dates i want to fetch record like below:
d1 d2 d31
jan feb dec
count sales amt avgsales count sales amt avgsales ------------------ count sales amt avgsales
so can anyone tell me what approach i shouls apply..
Thanks
abhishekThis forum is titled "Certification" - pl post in the PL/SQL or Database General forums for a better/faster response.
HTH
Srini -
Convert date value in 1 column help
Am on 10g.
I have a column: STAMP_DATE with these values:
I need to leave LEGACY as it is, but everything else, I need to convert it to: MMYYYY as in: 092010 for example.
So 9-Sep stands for Sep-2009. The digit is the year, I am trying to fix this.
Any SQL help would be appreciated, thank you!
STAMP_DATE
"LEGACY"
"9-Sep"
"9-Oct"
"9-Nov"
"9-May"
"9-Mar"
"9-Jun"
"9-Jul"
"9-Dec"
"9-Aug"
"9-Apr"
"10-May"
"10-Mar"
"10-Jan"
"10-Feb"
"10-Apr"
These values were imported from Excel using SQLLDR, so it kinda made them like that.maybe this might help.
SQL> select to_char(to_date(lg.stamp_date||'-'||to_char(sysdate,'yyyy'),'dd-mon-yyyy'),'mmyyyy') STAMP_DATE
2 from (select 'LEGACY' STAMP_DATE from dual union all
3 select '9-Sep' STAMP_DATE from dual union all
4 select '9-Oct' STAMP_DATE from dual union all
5 select '9-Nov' STAMP_DATE from dual union all
6 select '9-May' STAMP_DATE from dual union all
7 select '9-Mar' STAMP_DATE from dual union all
8 select '9-Jun' STAMP_DATE from dual union all
9 select '9-Jul' STAMP_DATE from dual union all
10 select '9-Dec' STAMP_DATE from dual union all
11 select '9-Aug' STAMP_DATE from dual union all
12 select '9-Apr' STAMP_DATE from dual union all
13 select '10-May' STAMP_DATE from dual union all
14 select '10-Mar' STAMP_DATE from dual union all
15 select '10-Jan' STAMP_DATE from dual union all
16 select '10-Feb' STAMP_DATE from dual union all
17 select '10-Apr' STAMP_DATE from dual) lg
18 where lg.stamp_date != 'LEGACY'
19 union all
20 select lg.stamp_date STAMP_DATE
21 from (select 'LEGACY' STAMP_DATE from dual union all
22 select '9-Sep' STAMP_DATE from dual union all
23 select '9-Oct' STAMP_DATE from dual union all
24 select '9-Nov' STAMP_DATE from dual union all
25 select '9-May' STAMP_DATE from dual union all
26 select '9-Mar' STAMP_DATE from dual union all
27 select '9-Jun' STAMP_DATE from dual union all
28 select '9-Jul' STAMP_DATE from dual union all
29 select '9-Dec' STAMP_DATE from dual union all
30 select '9-Aug' STAMP_DATE from dual union all
31 select '9-Apr' STAMP_DATE from dual union all
32 select '10-May' STAMP_DATE from dual union all
33 select '10-Mar' STAMP_DATE from dual union all
34 select '10-Jan' STAMP_DATE from dual union all
35 select '10-Feb' STAMP_DATE from dual union all
36 select '10-Apr' STAMP_DATE from dual) lg
37 where lg.stamp_date = 'LEGACY';
STAMP_DATE
092010
102010
112010
052010
032010
062010
072010
122010
082010
042010
052010
032010
012010
022010
042010
LEGACY
16 rows selected
SQL> -
Convert Values in Rows to Columns
Hi, i have a table with information of work handled. Example shown below.
ID | Key | Value
1 | Agent | 123
2 | Start | 01/12/12 01:52
3 | End | 01/12/12 01:56
What I would like to do is the information in the Column Key to become Column Headers and the values underneath i.e.
ID | Agent | Start | End
1 | 123 | 01/12/12 01:52 | 01/12/12 01:56
but not sure how i can write this in a query.
Any advice would be appreciated.
Thanks in advanceHi, thanks guys for your replies. I have managed to write some code (through loads of google searching and this forum) that allows me to view the agent that has dealt with a task, i have also added a case where if a task has been handled by 2 agents than to show me this as well.
select id, id2, time1, name, time2,
max(case when ord=1 then agent time2) as agent1,
max(case when ord=2 then agent time2) as agent2
from
select i3.id, i3.id2, i3.time1, i3.name, i3.time2, i4.value as agent,
dense_rank() over(partition by i3.id order by to_date(i4.created, 'DD/MM/YYYY HH24:MI:SS')) as ord
from i_info_3 i3
left join i_info_4 i4
on i3.id=i4.id
and i4.key='Agent'
order by i3.id
) r
group by id, id2, time1, name, time2
;this now gives me 2 extra columns with agent1 and agent2 and their values. The only thing i am trying to do is add the start and end data from the column called key. I thought I could use the same approach as the following:
i4.value as agent, i4.value as startand further on:
and i4.key='Start'but that wont work and i'm guessing cos i have repeated the .value. Any ideas on how i can get this added?
Thanks btw for all your help guys..
Really appreciated. -
Convert rows to Columns in Oracle
Hi,
The table like
Trx Date
PO121 23/11/2008
PO122 24/11/2008
PO123 25/11/2008
I want to convert all the rows to columns like the below table
PO121 23/11/2008 PO122 24/11/2008 PO123 25/11/2008
Is it possible in Oracle ?Like this
SQL> WITH T
2 AS
3 (
4 SELECT 'PO121 23/11/2008' VAL FROM DUAL
5 UNION ALL
6 SELECT 'PO122 24/11/2008' FROM DUAL
7 UNION ALL
8 SELECT 'PO123 25/11/2008' FROM DUAL
9 )
10 SELECT MAX(DECODE(RNO,1,VAL)) VAL1, MAX(DECODE(RNO,2,VAL)) VAL2, MAX(DECODE(RNO,3,VAL)) VAL3
11 FROM (SELECT ROW_NUMBER() OVER(ORDER BY VAL) RNO, VAL
12 FROM T)
13 /
VAL1 VAL2 VAL3
PO121 23/11/2008 PO122 24/11/2008 PO123 25/11/2008But beware the number of column must be known. without that you cant do it in a static SQL.
Edited by: Karthick_Arp on Nov 10, 2008 1:41 AM -
How to Convert Rows to Column in Query
Dear All,
I'm having problems in converting the data from rows into columns. Eg:
- item A sold on 01/01/07 = 5 kg
- item A sold on 10/01/07 = 5 kg
total item A sold in "JAN" = 10kg
- item A sold on 01/03/07 = 20 kg
total item A sold in "Mar" = 20kg
I did a query and it appear as below (in which I need the period as column)
Item Qty Period
A 10 2007-01
A 20 2007-03
The output I need is :
Item Jan Feb Mar
A 10 - 20
I've refer to the query posted in "Item History Query", even though I can get the column from Jan - Dec, but the total quantity for each month is not accurate. Please advise, and thanks for your time.
Cheers,
SereneHello Serene,
The Quantities will not be correct because you are using a Period Code in the Selection Criteria but it is not checked in the Select Statement.
But rewriting the code would cause duplicate entries for each item per months because of how the Group by clause works.
CHECK THIS
SELECT T1.ItemCode, T1.Dscription,
(SELECT SUM(QUANTITY) FROM INV1 WHERE MONTH(DOCDATE) = 1 AND ITEMCODE = T1.ItemCode AND DOCDATE >= T2.F_RefDate AND DOCDATE <= T_RefDate) AS 'JAN',
(SELECT SUM(QUANTITY) FROM INV1 WHERE MONTH(DOCDATE) = 2 AND ITEMCODE = T1.ItemCode AND DOCDATE >= T2.F_RefDate AND DOCDATE <= T_RefDate) AS 'FEB',
(SELECT SUM(QUANTITY) FROM INV1 WHERE MONTH(DOCDATE) = 3 AND ITEMCODE = T1.ItemCode AND DOCDATE >= T2.F_RefDate AND DOCDATE <= T_RefDate) AS 'MAR',
(SELECT SUM(QUANTITY) FROM INV1 WHERE MONTH(DOCDATE) = 4 AND ITEMCODE = T1.ItemCode AND DOCDATE >= T2.F_RefDate AND DOCDATE <= T_RefDate) AS 'APR',
(SELECT SUM(QUANTITY) FROM INV1 WHERE MONTH(DOCDATE) = 5 AND ITEMCODE = T1.ItemCode AND DOCDATE >= T2.F_RefDate AND DOCDATE <= T_RefDate) AS 'MAY',
(SELECT SUM(QUANTITY) FROM INV1 WHERE MONTH(DOCDATE) = 6 AND ITEMCODE = T1.ItemCode AND DOCDATE >= T2.F_RefDate AND DOCDATE <= T_RefDate) AS 'JUN',
(SELECT SUM(QUANTITY) FROM INV1 WHERE MONTH(DOCDATE) = 7 AND ITEMCODE = T1.ItemCode AND DOCDATE >= T2.F_RefDate AND DOCDATE <= T_RefDate) AS 'JUL',
(SELECT SUM(QUANTITY) FROM INV1 WHERE MONTH(DOCDATE) = 8 AND ITEMCODE = T1.ItemCode AND DOCDATE >= T2.F_RefDate AND DOCDATE <= T_RefDate) AS 'AUG',
(SELECT SUM(QUANTITY) FROM INV1 WHERE MONTH(DOCDATE) = 9 AND ITEMCODE = T1.ItemCode AND DOCDATE >= T2.F_RefDate AND DOCDATE <= T_RefDate) AS 'SEP',
(SELECT SUM(QUANTITY) FROM INV1 WHERE MONTH(DOCDATE) = 10 AND ITEMCODE = T1.ItemCode AND DOCDATE >= T2.F_RefDate AND DOCDATE <= T_RefDate) AS 'OCT',
(SELECT SUM(QUANTITY) FROM INV1 WHERE MONTH(DOCDATE) = 11 AND ITEMCODE = T1.ItemCode AND DOCDATE >= T2.F_RefDate AND DOCDATE <= T_RefDate) AS 'NOV',
(SELECT SUM(QUANTITY) FROM INV1 WHERE MONTH(DOCDATE) = 12 AND ITEMCODE = T1.ItemCode AND DOCDATE >= T2.F_RefDate AND DOCDATE <= T_RefDate) AS 'DEC',
(SELECT SUM(QUANTITY) FROM INV1 WHERE ITEMCODE = T1.ItemCode AND DOCDATE >= T2.F_RefDate AND DOCDATE <= T_RefDate) AS 'TOTAL'
FROM OINV T0 INNER JOIN INV1 T1 ON T0.DocEntry = T1.DocEntry INNER JOIN OFPR T2 ON T0.FinncPriod = T2.AbsEntry
WHERE T0.CardName ='[%A]' AND T2.Code >='[%1]' AND T2.Code <='[%2]'
GROUP BY T1.ItemCode, T1.Dscription, T2.F_RefDate, T2.T_RefDate
The Only way out of this is to declare Variable and Assign the F_RefDate and T_RefDate and then use the variables in the Select Statements.
Suda -
Internal table rows to columns
hi
i have an internal table with foll strcuture
customer jan feb mar apr jun july aug sep oct nov dec
a 1 2 3 4 5 6 7 8 9 10 11
b
c
n
i need to form another internal table whose ouput will be
month custA cust B custc cust d
jan 1
feb 2
mar 3
so depending upon the no of records of first internal table, columns need to be created in the new table with corresponding cusomters data.
how to proceed ?Check the links -
converting columns to rows
Convert Internal table Rows into columns of another internal table
Re: Moving columns of an internal table to rows of an another internal table.
Regards,
Amit
Reward all helpful replies. -
Hi,
I've got a challenge. I need to select row data as columns.
Suppose, I have this:
CREATE TABLE master
id NUMBER,
name VARCHAR2(50),
CONSTRAINT pk_master PRIMARY KEY(id)
CREATE TABLE detail
id NUMBER,
master_id,
type VARCHAR2(10),
value NUMBER,
CONSTRAINT pk_detail PRIMARY KEY(id),
CONSTRAINT fk_master FOREIGN KEY(master_id)
REFERENCES master(id),
CONSTRAINT c_type CHECK (type IN ('apple','orange'))
);Now, suppose master and detail holds the following data:
Master:
ID NAME
1 Jill
2 Jack
Detail:
ID MASTER_ID TYPE VALUE
1 1 apple 120
2 1 orange 230
3 2 apple 10Here comes the challenge: what do I have to put in a selectstatement, to get this result:
NAME APPLE ORANGE
Jill 120 230
Jack 10I know what types there are up front (only apple and orrange), so the query may use that knowledge.
Bonus guru points however to the one who can make a generic query that can convert the type rows into columns generically, regardless of what and how many types there are.scott@ORA92> -- test data:
scott@ORA92> SELECT * FROM master
2 /
ID NAME
1 Jill
2 Jack
scott@ORA92> SELECT * FROM detail
2 /
ID MASTER_ID TYPE VALUE
1 1 apple 120
2 1 orange 230
3 2 apple 10
scott@ORA92> -- PL/SQL for any number of values of type (apple, orange, etc.):
scott@ORA92> VARIABLE g_ref REFCURSOR
scott@ORA92> DECLARE
2 v_sql VARCHAR2(32767);
3 BEGIN
4 v_sql := 'SELECT master.name';
5 FOR rec IN (SELECT DISTINCT type FROM detail) LOOP
6 v_sql := v_sql
7 || ',SUM(DECODE(type,''' || rec.type || ''',value)) ' || rec.type;
8 END LOOP;
9 v_sql := v_sql
10 || ' FROM master, detail'
11 || ' WHERE master.id = detail.master_id'
12 || ' GROUP BY master.name';
13 OPEN :g_ref FOR v_sql;
14 END;
15 /
PL/SQL procedure successfully completed.
scott@ORA92> PRINT g_ref
NAME APPLE ORANGE
Jack 10
Jill 120 230
scott@ORA92> -
Convert one record row into multiple rows
Hi,
I have small requirement.I have selected one data base record into an internal table.Now internal table has 1 record i.e 1 row(ex: 10 columns). Now i will convert this single row record into multiple records i.e 10 rows( 10 columns wil; be converted into 10 rows). How i will convert this. Please give me any idea on this.
Regards
GeethaHi Geetha,
Search SCN using keyword, " convert Rows into columns" or vice versa,,,
U will get more answers & solutions,
Look at Some of the Previous threads....
Re: How to create a structure of itab as rows as colums and columns rows dy
Re: Transpose rows and columns
CONVERT ROWS INTO COLUMNS IN INTERNAL TABLE
Convert Internal table Rows into columns of another internal table
how to convert columns of an internal table to rows of another internal tab.
Convert Columns into Rows (internal tables) - Urgent Help Pleasse..
converting columns to rows
Thanks & regards,
Dileep .C
Maybe you are looking for
-
How to download a clob file from a table to my local drive?
Hii Everyone, I'm havig a table of this structure Create table r_dummy c_clob_file clob How to download this file into my local drive?Please give me some hints.Can this be done using dbms_lob?? Regards Raghu.
-
What is the best way to back up itunes library
I have my imac time machine program set to back up my computer every day to an external hard drive. I recently updated itunes and I lost some of my songs. I tried to find them in time machine but I couldn't find them. itunes support was good and I wa
-
How to install and configure the SQL Server
Hi All, We have to install SQL server in the new server because the old server is crash and need to upgrade. Please advice How to install and configure the SQL Server to run SAP Business One 8.8 successfully and what part we do have to give attention
-
Trouble with 5310 internet settings
Hi, ive recently bought a nokia 5310 and have downloaded all the correct settings for me to send and receive multimedia messages aswell access the internet. These all work, however I am unable to access the nokia.com homepage, im unable to create an
-
Subquery in dynamic where-clause
Hi, i'm trying to build a dynamic sql-statement in OPEN SQL, which uses a subquery in the dynamic where-clause. In the following example code the first select works fine, the second one raises an error. report zerrorforum. data: l_var_anzahl * No