Transpose row to column
database version: 10g
Table info: have table with 315 columns
So a record has a 315 column. I like to convert a row into a 315 rows.
Can any one tell what be best way to do that?
Thanks
sajjad
Hi, Sajjad,
Welcome to the forum!
What you want is called unpivot .
In any version, you can cross-join with a table that has 315 rows, like this
WITH cntr AS
SELECT LEVEL AS n
FROM dual
CONNECT BY LEVEL <= 315
SELECT id
, n
, CASE n
WHEN 1 THEN col_1
WHEN 1 THEN TO_CHAR (col_2) -- If col_2 is a NUMBER
WHEN 1 THEN TO_CHAR (col_3, 'YYYY-MM-DD HH24:MI"SS') -- If col_3 is a DATE
END AS data
FROM table_x
CROSS JOIN cntr
{code}
CASE can only have 128 WHEN clauses, so you may have to nest them.
Too bad you're not using Oracle 11: it has an UNPIVOT feature in the SELECT command to do this.
Similar Messages
-
Transpose rows to columns with numeric column name
I am trying to transpose row to columns.
Here is my data having 3 columns (date, last_retry and count(*) )
Date last_retry count(*)
1/2/06 2 13
1/2/06 1 5
5/5/06 1 12
5/5/06 2 9
Desired Output with columns ( date, 1, 2)
Date 1 2
1/2/06 5 13
5/5/06 12 9
Here is my query which doesn't work
select trunc(Date),
max(Decode(last_retry,'1',count(*))) as 1,
max(Decode(last_retry,'2',count(*))) as 2
from retry_state
1st problem: How do I transpose if this is not correct?
2nd problem: 1 cannot be named as column name, how can I name the columns
3rd problem: Suppose I am selecting this data and loading into a table. Now can
the data be loaded during select as well as transposed at the same time or would I need to create a view to load the data first into table and then perform transpose?hi,
this will transpose your data and insert into the table:
INSERT INTO transposed_table
(SELECT my_date,
MAX(DECODE(last_retry,1,cnt,0)) AS "1",
MAX(DECODE(last_retry,2,cnt,0)) AS "2"
FROM retry_state
GROUP BY my_date)
note: to avoid problem and confusion, i renamed the fields DATE and COUNT(*) to MY_DATE and CNT respectively. You should avoid using reserved words as your fields such as DATE!
hope this helps. -
Transpose row to column in APD
I am trying to transpose rows of records to column.
Original data:
Period ID Price 1 Price 2
200702 100 300 200
200702 101 250 100
200801 122 500 250
Need the above data to be transposed to:
Period ID Value
200702 100 300
200702 100 200
200702 101 250
200702 101 100
200801 122 500
200801 122 250
I have tried APD transformation "Data Records into Lists" without success. I am not sure what I am doing.
Does any one have a detail documnet on how to accomplish the task.
Thank you.
TonyHi Tony,
just check this link,
https://www.sdn.sap.com/irj/sdn/advancedsearch?cat=sdn_all&query=transposeinAPD&adv=false&sortby=cm_rnd_rankvalue
Hope it wil solve ur issue
thanks and regards
Bala -
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 -
How to transpose rows to columns and columns to rows in alv grid
can u plz tell me in alv grid how to
display data from itab having data
1
2
3 and so on
how to print in alv in a single row ie
1 2 3 and so onchk this code...
REPORT Z_TRANSPOSEALV .
* Type pools declaration for ALV
TYPE-POOLS: slis.
*Declarations for ALV, dynamic table and col no for transpose
DATA: l_col TYPE sy-tabix,
l_structure TYPE REF TO data,
l_dyntable TYPE REF TO data,
wa_lvc_cat TYPE lvc_s_fcat,
lt_lvc_cat TYPE lvc_t_fcat,
lt_fieldcatalogue TYPE slis_t_fieldcat_alv,
wa_fieldcat TYPE slis_fieldcat_alv,
lt_fieldcat TYPE slis_t_fieldcat_alv,
lt_layout TYPE slis_layout_alv.
*Field symbols declarations
FIELD-SYMBOLS :
<header> TYPE ANY,
<dynheader> TYPE ANY,
<dyndata> TYPE ANY,
<ls_table> TYPE ANY,
<dynamictable> TYPE STANDARD TABLE,
<it_table> TYPE STANDARD TABLE.
*Input the name of the table
PARAMETERS p_table TYPE dd02l-tabname OBLIGATORY.
*Initialization event
INITIALIZATION.
*Start of selection event
START-OF-SELECTION.
* Create internal table of dynamic type
CREATE DATA l_dyntable TYPE STANDARD TABLE OF (p_table)
WITH NON-UNIQUE DEFAULT KEY.
ASSIGN l_dyntable->* TO <it_table>.
*select statement to select data from the table as input into
*our dynamic internal table.
*Here i have restricted only till 5 rows.
*You can set a variable and give no of rows to be fetched
*The variable can be set in your select statement
SELECT * INTO CORRESPONDING FIELDS OF TABLE <it_table>
FROM (p_table) up to 5 rows.
*Fieldcatalogue definitions
wa_lvc_cat-fieldname = 'COLUMNTEXT'.
wa_lvc_cat-ref_table = 'LVC_S_DETA'.
APPEND wa_lvc_cat TO lt_lvc_cat.
wa_fieldcat-fieldname = 'COLUMNTEXT'.
wa_fieldcat-ref_tabname = 'LVC_S_DETA'.
wa_fieldcat-key = 'X'..
APPEND wa_fieldcat TO lt_fieldcat.
DESCRIBE TABLE <it_table>.
DO sy-tfill TIMES.
* For each line, a column 'VALUEx' is created in the fieldcatalog
* Build Fieldcatalog
WRITE sy-index TO wa_lvc_cat-fieldname LEFT-JUSTIFIED.
CONCATENATE 'VALUE' wa_lvc_cat-fieldname
INTO wa_lvc_cat-fieldname.
wa_lvc_cat-ref_field = 'VALUE'.
wa_lvc_cat-ref_table = 'LVC_S_DETA'.
APPEND wa_lvc_cat TO lt_lvc_cat.
* Build Fieldcatalog
CLEAR wa_fieldcat.
wa_fieldcat-fieldname = wa_lvc_cat-fieldname.
wa_fieldcat-ref_fieldname = 'VALUE'.
wa_fieldcat-ref_tabname = 'LVC_S_DETA'.
APPEND wa_fieldcat TO lt_fieldcat.
ENDDO.
* Create dynamic internal table
CALL METHOD cl_alv_table_create=>create_dynamic_table
EXPORTING
it_fieldcatalog = lt_lvc_cat
IMPORTING
ep_table = l_dyntable. ASSIGN l_dyntable->* TO <dynamictable>.
* Create structure as structure of the internal table
CREATE DATA l_structure LIKE LINE OF <dynamictable>.
ASSIGN l_structure->* TO <header>.
* Create structure = structure of the internal table
CREATE DATA l_structure LIKE LINE OF <it_table>.
ASSIGN l_structure->* TO <ls_table>.
* Create field catalog from our table structure
CALL FUNCTION 'REUSE_ALV_FIELDCATALOG_MERGE'
EXPORTING
i_structure_name = p_table
CHANGING
ct_fieldcat = lt_fieldcatalogue
EXCEPTIONS
inconsistent_interface = 1
program_error = 2
OTHERS = 3.
IF sy-subrc <> 0.
MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
ENDIF. DESCRIBE TABLE lt_fieldcatalogue.
* Fill the internal to display <dynamictable>
DO sy-tfill TIMES.
IF sy-index = 1.
READ TABLE lt_fieldcatalogue INTO wa_fieldcat INDEX 1.
ENDIF.
* For each field of it_table
ASSIGN COMPONENT 1 OF STRUCTURE <header> TO <dynheader>.
IF sy-subrc NE 0. EXIT .ENDIF.
READ TABLE lt_fieldcatalogue INTO wa_fieldcat INDEX sy-index.
* Fill 1st column
<dynheader> = wa_fieldcat-seltext_m.
IF <dynheader> IS INITIAL.
<dynheader> = wa_fieldcat-fieldname.
ENDIF.
*Filling the other columns
LOOP AT <it_table> INTO <ls_table>.
l_col = sy-tabix + 1.
ASSIGN COMPONENT sy-index OF STRUCTURE <ls_table> TO <dyndata>.
IF sy-subrc NE 0. EXIT .ENDIF.
ASSIGN COMPONENT l_col OF STRUCTURE <header> TO
<dynheader>.
IF sy-subrc NE 0. EXIT .ENDIF.
WRITE <dyndata> TO <dynheader> LEFT-JUSTIFIED.
ENDLOOP.
APPEND <header> TO <dynamictable>.
ENDDO.
*Layout for ALV output
lt_layout-zebra = 'X'.
lt_layout-no_colhead = 'X'..
lt_layout-colwidth_optimize ='X'.
lt_layout-window_titlebar = 'ALV GRID TRANSPOSED'.
*ALV Grid output for display
CALL FUNCTION 'REUSE_ALV_GRID_DISPLAY'
EXPORTING
is_layout = lt_layout
it_fieldcat = lt_fieldcat
TABLES
t_outtab = <dynamictable>. -
How to transpose Row to Column heading
Hi,
I have a table with following data.
ID COLUMN_NAME COLUMN_DATA
198 LAST_NAME OConnell
198 HIRE_DATE 6/21/1999
198 JOB_ID SH_CLERK
198 FIRST_NAME Donald
198 DEPARTMENT_ID 50
199 FIRST_NAME Jennifer
199 LAST_NAME Whalen
199 HIRE_DATE 9/17/1987
199 JOB_ID AD_ASST
199 DEPARTMENT_ID 10
I want to transpose the data in the field column_name as column heading and corresponding data in the field column_data as row under it.
Thanks $ Regards
ManishaIf you have 11g, you can do this...
With T As (
select '198' ID ,'LAST_NAME' COLUMN_NAME ,'OConnell' COLUMN_DATA from dual union all
select '198','HIRE_DATE','6/21/1999' from dual union all
select '198','JOB_ID','SH_CLERK' from dual union all
select '198','FIRST_NAME','Donald' from dual union all
select '198','DEPARTMENT_ID','50' from dual union all
select '199','FIRST_NAME','Jennifer' from dual union all
select '199','LAST_NAME','Whalen' from dual union all
select '199','HIRE_DATE','9/17/1987' from dual union all
select '199','JOB_ID','AD_ASST' from dual union all
select '199','DEPARTMENT_ID','10' from dual
--End of sample data
select ID,LAST_NAME,HIRE_DATE,JOB_ID,FIRST_NAME,DEPARTMENT_ID from T
pivot (max(column_data) for
column_name in ('LAST_NAME' as LAST_NAME,'HIRE_DATE' as HIRE_DATE,'JOB_ID' as JOB_ID,'FIRST_NAME' as FIRST_NAME,'DEPARTMENT_ID' as DEPARTMENT_ID))
ID LAST_NAME HIRE_DATE JOB_ID FIRST_NAM DEPARTMEN
198 OConnell 6/21/1999 SH_CLERK Donald 50
199 Whalen 9/17/1987 AD_ASST Jennifer 10
Elapsed: 00:00:00.00or if 10g or older
With T As (
select '198' ID ,'LAST_NAME' COLUMN_NAME ,'OConnell' COLUMN_DATA from dual union all
select '198','HIRE_DATE','6/21/1999' from dual union all
select '198','JOB_ID','SH_CLERK' from dual union all
select '198','FIRST_NAME','Donald' from dual union all
select '198','DEPARTMENT_ID','50' from dual union all
select '199','FIRST_NAME','Jennifer' from dual union all
select '199','LAST_NAME','Whalen' from dual union all
select '199','HIRE_DATE','9/17/1987' from dual union all
select '199','JOB_ID','AD_ASST' from dual union all
select '199','DEPARTMENT_ID','10' from dual
--End of sample data
select * from (
select id,
max(decode(column_name,'LAST_NAME', COLUMN_DATA)) LAST_NAME,
max(decode(column_name,'HIRE_DATE', COLUMN_DATA)) HIRE_DATE,
max(decode(column_name,'JOB_ID', COLUMN_DATA)) JOB_ID,
max(decode(column_name,'FIRST_NAME', COLUMN_DATA)) FIRST_NAME,
max(decode(column_name,'DEPARTMENT_ID', COLUMN_DATA)) DEPARTMENT_ID
from T group by id)
order by ID
PRAZY@11gR1> /
ID LAST_NAME HIRE_DATE JOB_ID FIRST_NAM DEPARTMEN
198 OConnell 6/21/1999 SH_CLERK Donald 50
199 Whalen 9/17/1987 AD_ASST Jennifer 10
Elapsed: 00:00:00.01Regards,
Prazy
Edited by: Prazy on Apr 5, 2010 3:32 PM
Added sql for older versions -
RESULT DATE1 ITEM
F 01-JUN-07 XYZ
F 01-JUL-07 XYZ
F 01-JUL-07 XYZ
F 01-JUL-07 XYZ
F 01-JUN-07 XYZ
F 01-JUN-07 ABC
F 01-JUN-07 ABC
F 01-JUL-07 ABC
F 01-JUL-07 ABC
P 01-JUL-07 ABC
P 01-JUL-07 ABC
P 01-JUN-07 ABC
P 01-JUN-07 ABC
P 01-JUN-07 ABC
the above rows has to be transposed to columns like below table from the above one. Which takes the total count of RESULT, count of "F" , count of "P" based on month and Product.
DATE1 ITEM TOTALCOUNT COUNT_OF_F COUNT_OF_P
01-JUN-07 XYZ 2 2 0
01-JUL-07 XYZ 3 3 0
01-JUN-07 ABC 5 2 3
01-JUL-07 ABC 4 2 2
Thanksuser9370033 wrote:
RESULT DATE1 ITEM
F 01-JUN-07 XYZ
F 01-JUL-07 XYZ
F 01-JUL-07 XYZ
F 01-JUL-07 XYZ
F 01-JUN-07 XYZ
F 01-JUN-07 ABC
F 01-JUN-07 ABC
F 01-JUL-07 ABC
F 01-JUL-07 ABC
P 01-JUL-07 ABC
P 01-JUL-07 ABC
P 01-JUN-07 ABC
P 01-JUN-07 ABC
P 01-JUN-07 ABC
the above rows has to be transposed to columns like below table from the above one. Which takes the total count of RESULT, count of "F" , count of "P" based on month and Product.
DATE1 ITEM TOTALCOUNT COUNT_OF_F COUNT_OF_P
01-JUN-07 XYZ 2 2 0
01-JUL-07 XYZ 3 3 0
01-JUN-07 ABC 5 2 3
01-JUL-07 ABC 4 2 2ThanksYou can do like this
select date1, item, count(*) totalcount, count(decode(result,'F',1,null)) count_of_f, count(decode(result, 'P',1, null)) count_of_p
from <table>
group
by date1, item -
with t as
(select 'Global' as ASSET_TYPE, NULL As ASSET_MASTER,NULL AS MILES_YARDS_FORMAT,
'NO PARENT ASSET FOUND' AS MSG_NO_PARENT,
'ASSET NOT WITHIN PARENT EXTENTS' AS MSG_OUT_OF_BOUNDS,
'MILES_FROM GREATER THAN MILES_TO' AS MSG_START_GT_END,
'ASSET HAS ZERO LENGTH' AS MSG_ZERO_LENGTH,
'OVERLAPPING ASSET - NOT CONTINUOUS EXTENTS' AS MSG_OVERLAP,
'ONE OR MORE KEY ATTRIBUTES CONTAIN NULL VALUE' AS MSG_NULL_VALUES from dual union all
select 'Ballast','XDF','000.0000',NULL,NULL,NULL,NULL,NULL,NULL from dual )
select * from t
I want the out put the above data to be transposed into single row. Null values should not be displayed.
Regards
PManik,
LISTAGG will not work below 11g...
Please Refer : <b>String Aggregation Techniques</b>
Try this -
WITH t AS
(SELECT 'Global' AS ASSET_TYPE,
NULL AS ASSET_MASTER,
NULL AS MILES_YARDS_FORMAT,
'NO PARENT ASSET FOUND' AS MSG_NO_PARENT,
'ASSET NOT WITHIN PARENT EXTENTS' AS MSG_OUT_OF_BOUNDS,
'MILES_FROM GREATER THAN MILES_TO' AS MSG_START_GT_END,
'ASSET HAS ZERO LENGTH' AS MSG_ZERO_LENGTH,
'OVERLAPPING ASSET - NOT CONTINUOUS EXTENTS' AS MSG_OVERLAP,
'ONE OR MORE KEY ATTRIBUTES CONTAIN NULL VALUE'
AS MSG_NULL_VALUES
FROM DUAL
UNION ALL
SELECT 'Ballast',
'XDF',
'000.0000',
NULL,
NULL,
NULL,
NULL,
NULL,
NULL
FROM DUAL)
SELECT /* listagg (asset_type, '') WITHIN GROUP (ORDER BY 1) ASSET_TYPE, */
RTRIM(XMLAgg(XMLElement(e, asset_type||', ')).EXTRACT('//text()'),', ') ASSET_TYPE,
MAX (ASSET_MASTER) ASSET_MASTER,
MAX (MILES_YARDS_FORMAT) MILES_YARDS_FORMAT,
MAX (MSG_NO_PARENT) MSG_NO_PARENT,
MAX (MSG_OUT_OF_BOUNDS) MSG_OUT_OF_BOUNDS,
MAX (MSG_START_GT_END) MSG_START_GT_END,
MAX (MSG_ZERO_LENGTH) MSG_ZERO_LENGTH,
MAX (MSG_OVERLAP) MSG_OVERLAP,
MAX (MSG_NULL_VALUES) MSG_NULL_VALUES
FROM t;gives
Global, Ballast XDF 000.0000 NO PARENT ASSET FOUND ASSET NOT WITHIN PARENT EXTENTS MILES_FROM GREATER THAN MILES_TO ASSET HAS ZERO LENGTH OVERLAPPING ASSET - NOT CONTINUOUS EXTENTS ONE OR MORE KEY ATTRIBUTES CONTAIN NULL VALUEEdited by: ranit B on Dec 28, 2012 12:23 PM
-- o/p added -
Hi All,
How can I achieve the desired result please.
create table #Tenant (GroupId int, ContactId INT, TenantName varchar(50) )
Iinsert into #Tenant values (1, 11, 'Mr Alan Glover')
Insert into #Tenant values (1, 12, 'Mrs Janet Glover')
insert into #Tenant values (2, 21, 'Mrs Cleet')
insert into #Tenant values (3, 31, 'Mr Dennis Slack')
insert into #Tenant values (3, 32, 'Mr Kevin Slack')
insert into #Tenant values (3, 33, 'Mrs Rosemary Slack')
select * from #Tenant
Desired Result
ContactGroupId
ContactId
Tenant1
Tenant2
Tenant3
Tenant4
1
11,12
Mr Alan Glover
Mrs Janet Glover
2
21
Mrs Cleet
3
31,32,33
Mr Dennis Slack
Mr Kevin Slack
Mrs Rosemary Slackwith cte
as
select *,
row_number () over (partition by groupid order by ContactId) rn from #Tenant
) select GroupId,(select cast(ContactId as varchar(20))+','
from cte c where c.GroupId=cte.GroupId order by GroupId
FOR XML PATH('') ) AS token,
max(case when rn=1 then TenantName end )Tenant1,
max(case when rn=2 then TenantName end )Tenant2,
max(case when rn=3 then TenantName end )Tenant3,
max(case when rn=4 then TenantName end )Tenant4
from cte
group by GroupId
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 -
SAP HANA View Row to Column Transpose
Hello Guys
What is the best way to transpose rows to columns within a Hana Model. I can find many articles that talk about Column to Row transpose.
Source:
Customer
Dim 1
Dim 2
1000
A
1100
1000
B
1200
1000
C
1300
Target:
Customer
A
B
C
1000
1100
1200
1300
ThanksNot as an answer, but as a question: Are there three rows *only* resp. could they be granted? Or you wanna have the amount dynamic, i.e. count the same customers and than created the amount of required columns?
-
Transposing SQL rows to columns
Hi All -
I have a query which returns result set as follows:
year amt_type amount
2001 vacation 1000
2001 medical 1000
2001 college 15000
2002 vacation 800
2002 medical 1000
2002 college 10000
2003 vacation 400
2003 medical 2000
2003 college 80000.
I am trying to make the years 2001, 2002, and 2003 as columns and trying to
achieve the below output
Amt type 2001 2002 2003
vacation 1000 800 400
medical 1000 1000 2000
college 15000 10000 8000
I am able to achieve this perfectly on client side. Right now I am trying to
achieve the same through using SQL. I am using
DECODE to achieve but my result set looks like below
Amt type 2001 2002 2003
vacation 1000
vacation 800
vacation 400
medical 1000
medical 1000
medical 2000
college 15000
college 10000
college 8000
I am trying this on oracle. I am new to this concept. can anyone who worked in
similar situation help me. Also, the years may change depending upon the dropdown
selection on client page. Can I transpose rows to columns in SQL for dynamic
values
Thankswith t as (
select 2001 year,'vacation' amt_type,1000 amount from dual union all
select 2001,'medical',1000 from dual union all
select 2001,'college',15000 from dual union all
select 2002,'vacation',800 from dual union all
select 2002,'medical',1000 from dual union all
select 2002,'college',10000 from dual union all
select 2003,'vacation',400 from dual union all
select 2003,'medical',2000 from dual union all
select 2003,'college',80000 from dual
select amt_type,
sum(case year when 2001 then amount end) "2001",
sum(case year when 2002 then amount end) "2002",
sum(case year when 2003 then amount end) "2003"
from t
group by amt_type
AMT_TYPE 2001 2002 2003
medical 1000 1000 2000
college 15000 10000 80000
vacation 1000 800 400
SQL> SY. -
How to transpose rows to multiple dynamic number of columns
Hi All,
I have a requirement to transpose the rows in single column to multiple columns. The columns are not fixed.
A table called XX_PRODUCT_SIZE.
The data in the table are,
PRODUCT_NO SIZE PRESSURE
P1 1 100
P1 1 200
P1 2 100
P1 2 300
P1 3 300
The data in the table are not fixed with respect to size and pressure. In future the product P1 may have size 4 with new pressure 900.
Now I want to convert these rows into multiple columns.
So it should be,
PRODUCT_NO SIZE_1 SIZE_2 SIZE_3 PRESSURE_100 PRESSURE_200 PRESSURE_300
P1 TRUE TRUE TRUE
P1 TRUE TRUE TRUE
P1 TRUE TRUE
I tried many ways of writing using CASE, MAX with rownumber over partition by etc. but which will not work for me as the rows are not fixed to compare.
Can you please help me writing a query which transpose rows to columns dynamically. My intention is to create a materialized view for this XX_PRODUCT_SIZE table with transposing columns.
I am using 10g DB
Thank You
Manju
Edited by: ManjuNaik88 on May 28, 2013 2:29 AMHi,
If the number of columns in a query has to be figured out at run-time, then you need dynamic SQL. See the froum FAQ {message:id=9360005} for links to examples.
You might find it easier to create one big column that looks like a variable number of columns. SELECT ... PIVOT can do this with XML output. String aggregation is another way; see {message:id=3527823} .
ManjuNaik88 wrote:
... I saw Oracle 11g Pivot can be used. "PIVOT" is still not working
SELECT ... PIVOT works. If it's not doing what you the way you're uisng it, then just change how you're using it.
(You don't expect a mor precise answer with just that information, do you?) -
Rows to columns/Transpose the records Query and Display output
hi ,
can anyone help me query this and transpose it to this format?
i am still a beginner in sql.
thanks for help!
Rows to columns/Transpose the records Query and Display output
id startdate endate
1111 1/2/2001 11/3/2001
1111 2/5/2002 4/3/2002
1111 2/6/2000 2/5/2001
3333 5/2/2003 11/3/2003
3333 6/2/2003 12/3/2003
3333 2/6/2005 2/5/2005
desired output
id startdate1 endate1 startdate2 endate2 startdate3 endate3
1111 1/2/2001 11/3/2001 2/5/2002 4/3/2002 2/6/2000 2/5/2001
3333 5/2/2003 11/3/2003 6/2/2003 12/3/2003 2/6/2005 2/5/2005Have you only 3 dates for each id ?
So, try :
SQL> l
1 with tbl as
2 (select 1111 as id, to_date('01/02/2001','DD/MM/YYYY') startdate, to_date('11/03/2001','DD/MM/YYYY') enddate from dual union all
3 select 1111 as id, to_date('02/05/2002','DD/MM/YYYY') startdate, to_date('04/03/2002','DD/MM/YYYY') enddate from dual union all
4 select 1111 as id, to_date('02/06/2000','DD/MM/YYYY') startdate, to_date('02/05/2001','DD/MM/YYYY') enddate from dual union all
5 select 3333 as id, to_date('05/02/2003','DD/MM/YYYY') startdate, to_date('11/03/2003','DD/MM/YYYY') enddate from dual union all
6 select 3333 as id, to_date('06/02/2003','DD/MM/YYYY') startdate, to_date('12/03/2003','DD/MM/YYYY') enddate from dual union all
7 select 3333 as id, to_date('02/06/2005','DD/MM/YYYY') startdate, to_date('02/05/2005','DD/MM/YYYY') enddate from dual )
8 select id, max(decode(dr,1,startdate)) start1,
9 max(decode(dr,1,enddate)) end1,
10 max(decode(dr,2,startdate)) start2,
11 max(decode(dr,2,enddate)) end2,
12 max(decode(dr,3,startdate)) start3,
13 max(decode(dr,3,enddate)) end3
14 from (select id, startdate,enddate, dense_rank() over (partition by id order by startdate) dr from tbl)
15* group by id
SQL> /
ID START1 END1 START2 END2 START3 END3
1111 02/06/00 02/05/01 01/02/01 11/03/01 02/05/02 04/03/02
3333 05/02/03 11/03/03 06/02/03 12/03/03 02/06/05 02/05/05
SQL> HTH,
Nicolas. -
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 -
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
Maybe you are looking for
-
Adobe Creative Cloud 2015: When Adobe Creative Cloud restart its trial for this year?
When Adobe Creative Cloud restart its trial for this year?
-
Something very bizarre is happening, and it doesn't make a lot of sense to me. Maybe someone here can offer a theory. Here's my setup, and here's what's been happening.... Mac Pro (early 2009), 2.66 GHz Quad-Core, 8 gigs of RAM, running Mac OS X 10.5
-
What is the best way of integrate a jsp aplication created in jdev 3.2.3 with portal
Hi, I've a jsp aplication made in jdeveloper 3.2.3 and i need to integrate this application into portal. What is the best way of doing this? thanks in advanced ricardo
-
Problems with JDBC on personal Java
Hi, I am a PhD student in Napier University and work with PDAs and Java. I have installed Jeode 1.9 Runtime Environment which is a certified implementation of 1.2 Personal Java on my HP IPAQ PDA. I have the following code that works fine on my deskto
-
Selective reordering of columns in a Jtable
Hi I have this problem where I need to allow the first 8 columns to be reordered but not the remaining columns in a Jtable. I have tried a few approaches by adding listeners to the jtable header and identifying the column which is clicked for reorder