From rows to columns
Hi all, i was wondering if there is a way to transform rows to column using analytical function. i know you can use min or max function and group by but would like to know if the same can be accomplish using analytical function. i am using oracle 9i
sample data
WITH table1 AS
SELECT 'AJD' id , 'BUNIT' code, 1000 myvalue FROM dual UNION all
SELECT 'AJD' id , 'BCAT' code, 2000 myvalue FROM dual UNION all
SELECT 'AJD' id , 'BLINE' code, 3000 myvalue FROM dual UNION all
SELECT 'AJD' id , 'BCEN' code, 4000 myvalue FROM dual UNION ALL
SELECT 'AAA' id , 'BUNIT' code, 5000 myvalue FROM dual UNION all
SELECT 'AAA' id , 'BCAT' code, 6000 myvalue FROM dual UNION all
SELECT 'AAA' id , 'BLINE' code, 7000 myvalue FROM dual UNION all
SELECT 'AAA' id , 'BCEN' code, 8000 myvalue FROM dual
desire output
ID UNIT CAT LINE CEN
ADJ 1000 2000 3000 4000
AAA 5000 6000 7000 8000
if this can be done using analytical function, please provide query if possible. thanks
Thanks for the sample data.
I'm not sure why you want to do this with analytic fiunctions instead of aggregates, it seems like a lot of effort for no gain, but this works on 9.2.0.8.0, and should work on other versions of 9i.
SQL> WITH table1 AS
2 (
3 SELECT 'AJD' id , 'BUNIT' code, 1000 myvalue FROM dual UNION all
4 SELECT 'AJD' id , 'BCAT' code, 2000 myvalue FROM dual UNION all
5 SELECT 'AJD' id , 'BLINE' code, 3000 myvalue FROM dual UNION all
6 SELECT 'AJD' id , 'BCEN' code, 4000 myvalue FROM dual UNION ALL
7 SELECT 'AAA' id , 'BUNIT' code, 5000 myvalue FROM dual UNION all
8 SELECT 'AAA' id , 'BCAT' code, 6000 myvalue FROM dual UNION all
9 SELECT 'AAA' id , 'BLINE' code, 7000 myvalue FROM dual UNION all
10 SELECT 'AAA' id , 'BCEN' code, 8000 myvalue FROM dual)
11 SELECT DISTINCT id, MAX(DECODE(code, 'BUNIT', myvalue)) OVER(PARTITION BY id) unit,
12 MAX(DECODE(code, 'BCAT', myvalue)) OVER(PARTITION BY id) cat,
13 MAX(DECODE(code, 'BLINE', myvalue)) OVER(PARTITION BY id) line,
14 MAX(DECODE(code, 'BCEN', myvalue)) OVER(PARTITION BY id) cen
15 FROM table1;
ID UNIT CAT LINE CEN
AJD 1000 2000 3000 4000
AAA 5000 6000 7000 8000John
Similar Messages
-
Converting key figures from rows to column using DSO and start routine
Hi SDNer:
I need some help to convert key figures from rows to column.
The source is DSO 1 and I am thinking about writing ABAP in the start routine to do the conversion. The target is DSO2.
Below is the more detail information with example. Basically, for each record in DSO 1 I need to create 3 records (because there are 3 KF's) and output to DSO2.
I would really appreciate some help on this.Thank you.
Tony
DSO 1 data format (SOURCE)
Period ID KF1 KF2 KF3
200702 100 300 200 750
Output to DSO 2 (TARGET)
Period ID KF LABEL
200702 100 300 KF1
200702 100 200 KF2
200702 100 750 KF3This is the code in BI 7.0.
u need to put a field "Label" in DSO1. u dont need to populate this in DSO1 but it helps the code to populate the field in DSO2.
DATA: wa_result TYPE _ty_s_sc_1,
t_result TYPE STANDARD TABLE OF _ty_s_sc_1.
DATA:counter(2) TYPE n.
LOOP AT SOURCE_PACKAGE INTO wa_result.
counter =0.
while counter < 3 .
wa_result- Period = wa_result-Period.
wa_result- ID = wa_result-ID.
if counter = 0.
wa_result- KF1 = wa_result-KF1.
wa_result- Label = 'KF1'.
elseif counter = 1.
wa_result- KF1 = wa_result-KF2.
wa_result- Label = 'KF2'.
else.
wa_result- KF1 = wa_result-KF3.
wa_result- Label = 'KF3'.
endif.
APPEND wa_result TO t_result.
counter = counter+1.
endwhile.
endloop.
CLEAR: SOURCE_PACKAGE,wa_result.
LOOP AT t_result INTO wa_result.
APPEND wa_result TO SOURCE_PACKAGE.
ENDLOOP. -
Converting from rows to columns
Converting Rows to Columns
We have one business requirment where they want to convert rows to columns. The data we are talking about is 2-3 TB of data. Data looks something in this format.
Table Structure
Date_1 Unit_Number Data_ID Data_Value
2013-01-02 00:00:00 100013 123 671
2013-01-02 00:00:00 100014 131 771
2013-01-02 00:00:00 100015 281 812
2013-01-02 00:00:00 100016 712 979
2013-01-02 00:00:00 100017 715 719
Pivoted table
Date_1 RY XY HJ KD IK GH HH KK TK RT ...
2013-01-02 00:00:00 671 771 812 979 719 979 719 980 799 79
2013-01-02 00:10:00 671 771 812 979 719 979 719 980 799 79
and so on
We are pivoting this data using query and creating view using query something like below
select a.date_1 date_1 a.unit_number system_number,
max(CASE WHEN a.data_id= 123 then a.DATA_Value END) RY,
max(CASE WHEN a.data_id= 281 then a.DATA_Value END) XY,
max(CASE WHEN a.data_id=712 then a.DATA_Value END) HJ,
max(CASE WHEN a.data_id=715 then a.DATA_Value END) KD,
max(CASE WHEN a.data_id=666 then a.DATA_Value END) IK,
max(CASE WHEN a.data_id=231 then a.DATA_Value END) GH,
max(CASE WHEN a.data_id=881 then a.DATA_Value END) HH,
max(CASE WHEN a.data_id=734 then a.DATA_Value END) KK,
max(CASE WHEN a.data_id=734 then a.DATA_Value END) TK,
max(CASE WHEN a.data_id=724 then a.DATA_Value END) TK,
from FROM table_name group by 1,2
We also tried pivot clause but still no major improvement in performance.
There are about 40 such rows that we are trying to convert into columns. We created indexes, Primary, Secondary and referencial ones to tune this overall query. Also added paritions, We find this conversion works fine for smaller query, however for larger set of data we get high CPU and IO and also often runs into spool error. The data set we are runing on this query are about 3-4 TB. There is another table where we have about 100 rows which we need to convert into one row and again size goes to 4-5 TB
Questions I have
1) Is there better way to convert columns to Rows?
2) What options can be use to reduce CPU, IO and Spool error?
3) Does Orage 11g datawarehouse any feature which will hellp us here
4) Any other appproach or design suggested here that will help us?
This design is pushed by our business due to flexibility this design offers and we are runing into performance and we are trying to make this work without impacting CPU, Spool and IO
Any suggestions would help us here, thanks for reading thisHi,
Here's one way to do that:
WITH got_times AS
SELECT MAX ( CASE
WHEN msg_line = 'LONGITUDINAL REFRESH HAS BEGUN'
THEN msg_datetime
) AS start_time
, MAX ( CASE
WHEN msg_line = 'LONGITUDINAL REFRESH HAS COMPLETED'
THEN msg_datetime
) AS end_time
FROM xxwv.xxwv_hsum_info_reports
SELECT start_time
, end_time
, (end_time - start_time) * 24 * 60 AS duration_minutes
FROM got_times
;When you run the two different (but very similar) to get the two times, you have two different WHERE clauses. You can combine those two similar queries into one, but whatever WHERE clause you have will apply to the whole query. Whenever you wish you could apply a WHERE clause just to one column, think of CASE instead. -
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 -
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 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. -
Transposing group from rows to column
Hi Team,
I am having groups of rows of a fixed kind that need to be transposed to column. eg
Attrib
Value
Attribute1
a
Attribute2
b
Attribute3
c
Attribute4
d
Attribute1
e
Attribute2
f
Attribute3
g
Attribute4
h
Attribute2
i
Attribute3
j
Attribute4
k
This need to be transposed as ;
Attribute1
Attribute2
Attribute3
Attribute4
a
b
c
d
e
f
g
h
NULL
i
j
k
Any help would be great...
I tried using PIVOT like
pivot (min (AttributeValue) for rn in ([1], [2], [3], [4],[5], [6])) pvt
where i was having rank in rn... but the places where Attribute1 is not present, that also nneed to become NULL. This is something I am not able to do.Hi
If
I may, there is very small fix to
Rishabh's query in order to make it work.
* as it is it will work only if the order of the insert fit the result, and not in any case! the SQL Server might bring the data in different order if there is no use of ORDER BY
Option 1:
;with cte as
SELECT * , ROW_NUMBER () OVER (partition by Attrib ORDER BY (SELECT NULL)) as rnum
FROM T
--select * from cte
select [Attribute1],[Attribute2],[Attribute3],[Attribute4]
FROM
SELECT Attrib,Value , rnum
FROM cte
)p
PIVOT
(MAX(value) FOR Attrib IN ([Attribute1],[Attribute2],[Attribute3],[Attribute4]))pvt
Option 2: Another option for solution might be
;with MyCTE as (
select Attrib, Value, ROW_NUMBER() OVER (partition by Attrib order by (SELECT NULL)) RN
from T
select
MAX(CASE when Attrib = 'Attribute1' then Value END) as Attribute1
,MAX(CASE when Attrib = 'Attribute2' then Value END) as Attribute2
,MAX(CASE when Attrib = 'Attribute3' then Value END) as Attribute3
,MAX(CASE when Attrib = 'Attribute4' then Value END) as Attribute4
--, RN
from MyCTE
group by RN
And here is all together (check your solution which is the first, it will not bring the correct result since I changed the order of inserted)
create table T (Attrib NVARCHAR(100), Value NVARCHAR(10))
insert T values
('Attribute1', 'a'),
('Attribute2', 'b'),
('Attribute3', 'j'),
('Attribute3', 'c'),
('Attribute4', 'd'),
('Attribute1', 'e'),
('Attribute2', 'f'),
('Attribute3', 'g'),
('Attribute4', 'h'),
('Attribute2', 'i'),
('Attribute4', 'k')
GO
;with cte as
SELECT * , (ROW_NUMBER () OVER (ORDER BY (SELECT NULL)) -1 )/ 4 as rnum
FROM T
--select * from cte
select [Attribute1],[Attribute2],[Attribute3],[Attribute4]
FROM
SELECT Attrib,Value , rnum
FROM cte
)p
PIVOT
(MAX(value) FOR Attrib IN ([Attribute1],[Attribute2],[Attribute3],[Attribute4]))pvt
GO -- Not OK
;with MyCTE as (
select Attrib, Value, ROW_NUMBER() OVER (partition by Attrib order by (SELECT NULL)) RN
from T
select
MAX(CASE when Attrib = 'Attribute1' then Value END) as Attribute1
,MAX(CASE when Attrib = 'Attribute2' then Value END) as Attribute2
,MAX(CASE when Attrib = 'Attribute3' then Value END) as Attribute3
,MAX(CASE when Attrib = 'Attribute4' then Value END) as Attribute4
--, RN
from MyCTE
group by RN
GO -- OK
;with cte as
SELECT * , ROW_NUMBER () OVER (partition by Attrib ORDER BY (SELECT NULL)) as rnum
FROM T
--select * from cte
select [Attribute1],[Attribute2],[Attribute3],[Attribute4]
FROM
SELECT Attrib,Value , rnum
FROM cte
)p
PIVOT
(MAX(value) FOR Attrib IN ([Attribute1],[Attribute2],[Attribute3],[Attribute4]))pvt
GO --OK
drop table T
Ronen Ariely
[Personal Site] [Blog] [Facebook] -
How to break first,last name from rows to columns?
drop table t1;
create table t1
(c1 varchar2(100)
insert into t1
values(' <First Name >david </First Name>');
insert into t1
values(' <Last Name > smith </Last Name >');
insert into t1
values(' <First Name >Harry </First Name >');
insert into t1
values('<Last Name > Bird </Last Name >');
select * from t1;
C1
<First Name >david </First Name>
<Last Name > smith </Last Name >
<First Name >Harry </First Name >
<Last Name > Bird </Last Name >
4 rows selected.
out put should be
First Last
David Smith
Harry Bird
ThanksIf homework I'd probably be looking at the string manipulation functions. If a real application I'd be looking at a different table design, and given that these look like xml tags that are or should be defined in a schema, using XMLDB.
Niall Litchfield
http://www.orawin.info/
drop table t1;
create table t1
(c1 varchar2(100)
nsert into t1
values(' <First Name >david </First Name>');
insert into t1
values(' <Last Name > smith </Last Name >');
insert into t1
values(' <First Name >Harry </First Name >');
insert into t1
values('<Last Name > Bird </Last Name >');
select * from t1;
C1
<First Name >david </First Name>
<Last Name > smith </Last Name >
<First Name >Harry </First Name >
<Last Name > Bird </Last Name >
4 rows selected.
out put should be
First Last
David Smith
Harry Bird
Thanks -
Is it possible to switch the rows and columns?
Is it possible to switch the rows and columns of a table? The reason I ask is that it would be easier for me to input the data with the number at the top of a column and the fields going down. But it would be easier to read the data with the number on the left and the fields going to the right. Is it possible to switch a table in this way?
mahongue wrote:
Is it possible to switch the rows and columns of a table? The reason I ask is
that it would be easier for me to input the data with the number at the top
of a column and the fields going down. But it would be easier to read the
data with the number on the left and the fields going to the right. Is it
possible to switch a table in this way?
It sounds to me as though you wish to transpose a table so that the original is changed from rows to columns and from columns to rows, as in the following:
Table 1
A B C
========
1 o p q
2 r s t
3 u v w
Table 2
A B C
========
1 o r u
2 p s v
3 q t w
You are right - it would be nice to have a menu item to magically transpose a selected block of cells. But there isn't one. So...
One way to solve this is to use the index() and transpose() functions to accomplish row and column cell transposition. If you are going to use a 1:1 cell correspondence and change the header columns and rows also, you can use this:
=INDEX(TRANSPOSE(Table # :: <range>),ROW(),COLUMN())
where Table # and <range> is substituted as in the following fashion:
=INDEX(TRANSPOSE(Table 1 :: $A$1:$C$3),ROW(),COLUMN())
Create a second table. Copy the modified formula above with the appropriate substitutions, select the range you wish to have your transposition inserted into (must match the transposed cell dimensions of the original range), paste the forumula and voila! the cells will be transposed.
Cautions:
o The target table must match the swapped cell length and width dimension. For example, if the original data range is 6 columns wide by 4 rows deep, then the corresponding table or range to hold the transposition must be 4 columns wide by 6 rows deep.
o If your transposed data block is to be offset from the origin of the new table, then you will need to include a subtractive offset into your cell formula, since in the transpose() function the data in the master data range is referenced from its position with the master range, not its cell position in the table. Such an offset is necessary because this example formula uses the target row and column numbers to arrive at indexed positions.
For example, if the new data range is to be offset one column to the right and one row below from the target table's origin then you must subtract (-1) from the cell and from the column references in the formula:
Example:
=INDEX(TRANSPOSE(Table 3 :: $B$2:$D$4),ROW()-1,COLUMN()-1)
If someone has a better solution I'd be glad to hear of it. -
Hi
I have folowing scenario. I am getting the result with some query like below :
STATE DAY AVG
NY 02/02 5
NY 02/03 10
NY 02/04 20
NY 02/05 15
IL 02/02 23
IL 02/03 34
IL 02/04 29
IL 02/05 9
FL 02/02 15
FL 02/03 8
FL 02/04 9
FL 02/05 10
and so on..Now I want to convert it from rows to column, but still want to keep STATE column group by :
so the result would be :
STATE 02/02 02/03 02/04 02/05
NY 5 10 20 15
IL 23 34 29 9
FL 15 8 9 10
and so on...I tried using pivot function, but it didnt work. is it even possible? or I will have to do it in code (.net c#) side.
Thanks1 WITH t AS (
2 SELECT 'NY' state,'02/02' mydt,5 myavg FROM dual
3 UNION all
4 SELECT 'NY','02/03',10 FROM dual
5 UNION all
6 SELECT 'NY','02/04',20 FROM dual
7 UNION all
8 SELECT 'NY','02/05',15 FROM dual
9 UNION all
10 SELECT 'IL','02/02',23 FROM dual
11 UNION all
12 SELECT 'IL','02/03',34 FROM dual
13 UNION all
14 SELECT 'IL','02/04',29 FROM dual
15 UNION all
16 SELECT 'IL','02/05',9 FROM dual
17 UNION all
18 SELECT 'FL','02/02',15 FROM dual
19 UNION all
20 SELECT 'FL','02/03',8 FROM dual
21 UNION all
22 SELECT 'FL','02/04',9 FROM dual
23 UNION all
24 SELECT 'FL','02/05',10 FROM dual
25 )
26 SELECT * FROM t
27 PIVOT
28 (
29 SUM(myavg)
30 FOR mydt IN('02/02','02/03','02/04','02/05')
31 )
32* ORDER BY state DESC
SQL> /
ST '02/02' '02/03' '02/04' '02/05'
NY 5 10 20 15
IL 23 34 29 9
FL 15 8 9 10Am I missing some thing here ? -
Rows to column and need to nvl for that newly columns
Hi,
I have to create rows to column query in rdf and in turn i have to created excel rtf template to produce excel output.
select max(decode (test.role, 'PA-ELT Member', test.full_name )) ELT_MEMBER,
max(decode (test.role, 'PA-IT Director', test.full_name )) IT_MEMBER,
max(decode (test.role, 'Project Manager', test.full_name )) Project_Manager,
TEST.segment1 project_NUMber,
test.name project_Name,
test.project_id,
test.project_type ,
test.organization_name,
TEST.project_status_name Status_Name,
TEST.start_date Start_date,
TEST.COMPLETION_DATE,
TEST.Planned_OOE,
TEST.Planned_Dep,
TEST.Planned_lab
from
(select
pppv.full_name,
pppv.role,
ppa.name,
ppa.project_id,
ppa.segment1,
ppa.project_type,
(select name from PA_ALL_ORG_V where organization_id = ppa.CARRYING_OUT_ORGANIZATION_ID) organization_name,
ppa.PROJECT_STATUS_CODE,
pps.PROJECT_STATUS_NAME,
ppa.START_DATE,
ppa.COMPLETION_DATE,
(select N_EXT_ATTR1 from PA_PROJECTS_ERP_EXT_B where project_id = ppa.project_id and ATTR_GROUP_ID = 243) Planned_OOE,
(select N_EXT_ATTR2 from PA_PROJECTS_ERP_EXT_B where project_id = ppa.project_id and ATTR_GROUP_ID = 243) Planned_Dep,
(select N_EXT_ATTR3 from PA_PROJECTS_ERP_EXT_B where project_id = ppa.project_id and ATTR_GROUP_ID = 243) Planned_lab
from
PA_PROJECTS_ALL ppa, PA_PROJECT_PLAYERS_V pppv, pa_project_statuses pps
where ppa.project_id = pppv.project_id
and ppa.PROJECT_STATUS_CODE = pps.PROJECT_STATUS_CODE
and pppv.role in ('PA-ELT Member','PA-IT Director','Project Manager')
and ppa.CARRYING_OUT_ORGANIZATION_ID=3994
)test
where 1=1
and TEST.project_type = nvl(:P_PROJECT_TYPE,test.project_type)
and TEST.project_status_name = nvl(:P_PROJECT_STATUS,test.project_status_name)
and TEST.segment1 = nvl(:P_PROJECT_NUMBER,test.segment1)
and TEST.full_name = nvl(:P_ELT_MEMBER, test.full_name)
and test.full_name = nvl(:P_IT_DIRECTOR,test.full_name)
and TEST.full_name = nvl(:P_PROJECT_MANAGER,test.full_name)
group by
TEST.segment1,
test.name,
test.project_id,
test.project_type,
test.organization_name,
TEST.project_status_name,
TEST.start_date,
TEST.COMPLETION_DATE,
TEST.Planned_OOE,
TEST.Planned_Dep,
TEST.Planned_lab
order by TEST.SEGMENT1
see ELT_MEMBER,IT_MEMBER and Project_Manager are columns created from rows to column.
now if i put where clause for this any columns for Eg: ELT_MEMBER it is giving Elt_member column values alone not remaining IT_member and Project Manager it show null even it has values .
it is because of this where clause
and TEST.full_name = nvl(:P_ELT_MEMBER, test.full_name)
and test.full_name = nvl(:P_IT_DIRECTOR,test.full_name)
and TEST.full_name = nvl(:P_PROJECT_MANAGER,test.full_name)
though i have ELT_MEMBER, IT_member and Project Manager column in where clause i have to call parent sql query column full_name.
i have tried to have nvl on column like below.
nvl( max(decode (test.role, 'Project Manager', test.full_name )),(select full_name from PA_PROJECT_PLAYERS_V where project_id = test.project_id and role ='Project Manager')) Project_Manager,
but it is showing error single -row subquery error .
it is possible to have a where clause for rows to columns .
Please help in this regardsSQL> ed
Wrote file afiedt.buf
1 with t as (select 'john,henry,michi,glen' as customer_name, 25000 as credit_limit from dual union all
2 select 'dilon,bryan', 10000 from dual union all
3 select 'raymond', 8000 from dual)
4 -- END OF TEST DATA
5 select regexp_substr(customer_name, '[^,]+', 1, rn) as customer_name, credit_limit
6 from t
7 ,(select rownum rn
8 from dual
9 connect by rownum <= (select max(length(regexp_replace(t.customer_name,'[^,]'))+1) from t))
10 where regexp_substr(customer_name, '[^,]+', 1, rn) is not null
11* order by credit_limit desc
SQL> /
CUSTOMER_NAME CREDIT_LIMIT
john 25000
henry 25000
michi 25000
glen 25000
bryan 10000
dilon 10000
raymond 8000
7 rows selected.
SQL>Just replace "t" with your query to select the data from the external table. -
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 -
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 can i open a PDF bank statement in "numbers" so that the rows and columns contain properly aligned data from statement?
Numbers can store pdfs pages or clippings but does not directly open pdf files. To get the bank statement into Numbers as a table I would open the bank statment in Preview (or Skim) or some pdf viewer.
Then hold the option key while selecting a column of data.
Then copy
Then switch to numbers and paste the column into a table
Then repeat for the other columns in the pdf document
It would be easier (in my opinion) to download the QFX or CSV version from your bank -
Display last value from a row or column?
I'm using Numbers 09 and want to display the last value entered in a column in another table.
For example in Table A I have columns set up by date with simple sums at the bottom of each column. I add new sums every day depending on the values from that day. What I'd like to do is get the last daily total and enter that value into another table called Table B. Is there a formula that will do that?
If I'm not being clear enough please let me know what additional information you need and I will be happy to provide it.
Thanks,
rkaufmann87rkaufmann87 wrote:
Hi Barry,
Thanks for posting the example, not quite though. In your sample Table A is transferring all the totals to Table B. What I'd like is as I enter the data in the columns in Table A Table B then picks up the latest update in a single cell. For example lets say Table A's Column A is May 1 and the total is 45, let's say that sum is placed in A15. Table B automatically picks up A15 from Table A and makes a duplicate in Table B cell A1, then the next day Table A's Column B is May 2 and the total is 90 (cell B15), then Table B senses the latest total is 90 and enters that in cell A1 again. Is this possible?
Here's another go.
Table 1 has a second Header row added (row 2) Cells in this row contain the formula
=IF(A1=MAX($1:1),COLUMN(),"")
Which returns the column number of the cell in row 1 containing the latest date. (4) This number is used by Table 2 to determine the column from which to return the total in the bottom (footer) row. (see below)
A1 in Table 2 and Table 3 contain the same formula:
=MAX(Table 1 :: $1:1)
This returns the latest date from row 1 of Table 1.
A2 in Table 2 and Table 3 contain formulas that return the value in the bottom cell of the column containing the latest date in row 1.
Table 2: =OFFSET(Table 1 :: $A$1,ROWS('May 1, 2010')-1,MAX(Table 1 :: $2:2)-1)
Table 3: =OFFSET(Table 1 :: $A$1,ROWS('May 1, 2010')-1,COUNT(Table 1 :: $1:1)-1)
Both use the same base ($A$1) and the same row offset (ROWS('May 1, 2010')-1) to reach the bottom row of Table 1.
Table 2 uses the maximum (and only) numerical value in row 2 of Table 1 ( MAX(Table 1 :: $2:2) ), then subtracts 1 to reach the fourth column of table 1.
Table 3 uses the same means to determine the row offset, but counts the number of dates entered into row 1 of Table 1 ( COUNT(Table 1 :: $1:1) ), then subtracts 1 to reach the same cell.
I prefer the method in Table 3 because it avoids the need for the second Header row and the possibility of overwriting the formulas in that row. (Row 2 of Table 1 may be deleted without affecting Table 3.) It does require that there be no empty cells in Row 1 from Column A to the column containing the latest date.
Regards,
Barry
Maybe you are looking for
-
AnyConnect issue with Cisco ASA 5505
I continue to bang my head against the wall on this one. Everytime I try to connect to the AnyConnect SSL VPN I get the following error "No address available for SVC connection" I have verified up and down that my VPN pool is there and assigned. I ha
-
CC automation problems with Battery 3
I have the knowledge about how CCs work as I've worked with hardware samples and Cubase for years. I just got myself a Macbook, Logic Exp 7.2 and Battery 3 (it's UB). In Battery 3, I can freely assign any CC to modulate some desired sampler parameter
-
WWhy I can't start up my MacBook pro, cant detect the power cord as well, no light indicated it's plugged in. Does anyone has same issue before and fixed it. It happened while i plugged in my iphone usb, mbp just gone off like that.
-
WE8MSWIN1252 Does it supports Arabic?
Hi All, One of the strange facts which we saw recently was a 8i database running with WE8MSWIN1252 supporting Arabic characters successfully. Users were happy with the data representation in Forms 6i too. Though we have 100's of threads which says AR
-
Dv6 series - DPC latency spikes
I currently have a Dell laptop with frequent DPC latency spikes. As a result, I will be returning the laptop for a new laptop that does not have those spikes. http://www.shopping.hp.com/webapp/shopping/product_detail.do?storeName=storefronts&landing=