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 this

Hi,
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.

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  KF3

    This 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.

  • 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 AM

    993012 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.

  • Group by and then convert form Row to column

    Hi All,
    below is a transaction table for bank customer.
    region_id     cutomer_id     transaction_type     transaction_date
    101          12345          CC               10-March-2011
    101          12345          DC               07-March-2011
    101          12345          P1               01-March-2011
    101          12345          p2               10-Jan-2011
    102          45678          CC               15-feb-2011
    101          12345          p3               27-OCT-2010with combinaton of region_id and customer_id, we get uniq record from the table. There are also different kind of transaction a customer has done. It is given in transaction_type column (CC - Credit card, Dc - Debit Card, and those start with P% {including P1, p2, p3} = payment).
    Now my requirement is to get the number of transaction for each transaction type for a current year and also number of total transaction by the customer. Below is my output table.
    region_id     cutomer_id     transaction_type     transaction_date     Tran_type_cc     Tran_type_DC     Tran_type_P     count_tran
    101          12345          CC               10-March-2011          1          1          2          5
    101          12345          DC               07-March-2011          1          1          2          5
    101          12345          P1               01-March-2011          1          1          2          5
    101          12345          p2               10-Jan-2011          1          1          2          5
    102          45678          CC               15-feb-2011          1          0          0          1
    101          12345          p3               27-OCT-2010          1          1          2          5if i do group by it gives me result but at row level and to convert row into column to get above result, i need to use decode function. My sourcec is containing 25 miliion records, and if i execute the query, it is getting hanged. Can someone help me how can i write a fine tuned query by using analytical function

    How about this?
    Note: I suppose, p1, P1, p2, P2, p3, P3 all belong to the same payment category regardless of their upper/lower case.
    Here is the table and the data:
    CREATE TABLE T1 (REGION_ID NUMBER, CUSTOMER_ID NUMBER, TRAN_TYPE VARCHAR2(5), TRAN_DATE DATE);
    INSERT INTO T1 VALUES (101, 12345, 'CC', TO_DATE('10-Mar-2011','DD-MON-YYYY'));
    INSERT INTO T1 VALUES (101, 12345, 'DC', TO_DATE('07-Mar-2011','DD-MON-YYYY'));
    INSERT INTO T1 VALUES (101, 12345, 'P1', TO_DATE('01-Mar-2011','DD-MON-YYYY'));
    INSERT INTO T1 VALUES (101, 12345, 'p2', TO_DATE('10-Jan-2011','DD-MON-YYYY'));
    INSERT INTO T1 VALUES (102, 45678, 'CC', TO_DATE('15-FEB-2011','DD-MON-YYYY'));
    INSERT INTO T1 VALUES (101, 12345, 'p3', TO_DATE('27-OCT-2010','DD-MON-YYYY'));Here is the query:
    SELECT REGION_ID, CUSTOMER_ID, TRAN_TYPE, TRAN_DATE
      , SUM(DECODE(TRAN_TYPE, 'CC', '1','0')) OVER (PARTITION BY CUSTOMER_ID) AS CC
      , SUM(DECODE(TRAN_TYPE, 'DC', '1', '0')) OVER (PARTITION BY CUSTOMER_ID ) AS DC
      , SUM(DECODE(SUBSTR(UPPER(TRAN_TYPE), 1,1) , 'P', '1','0')) OVER (PARTITION BY CUSTOMER_ID) AS P
      , SUM(1) OVER (PARTITION BY CUSTOMER_ID) AS TRAN_T
    FROM T1 ;
    r_id   cust_id      t_TYPE   T_DATE  CC_CNT  DC_CNT  P_CNT  T_CNT
    101     12345     CC     10-MAR-11     1     1     3     5
    101     12345     DC     07-MAR-11     1     1     3     5
    101     12345     p3     27-OCT-10     1     1     3     5
    101     12345     p2     10-JAN-11     1     1     3     5
    101     12345     P1     01-MAR-11     1     1     3     5
    102     45678     CC     15-FEB-11     1     0     0     1Edited by: PhoenixBai on Mar 14, 2011 4:16 PM

  • Need query to convert Single Row Multiple Columns To Multiple rows

    Hi,
    I have a table with single row like below
    Column0 | Column1 | Column2 | Column3 | Column4|
    Value0    | Value1    | Value2    | Value3    |  Value4  |
    Am looking for a query to convert above table data to multiple rows having column name and its value in each row as shown below
    Column0 | Value0
    Column1 | Value1
    Column2 | Value2
    Column3 | Value3
    Column4 | Value4
    Thanks in advance.
    Mohan

    Hi ykMohan,
    Dynamic UNPIVOT can be applied in this case as well.
    CREATE TABLE dbo.T(ID INT,Column0 VARCHAR(99),Column1 VARCHAR(99),Column2 VARCHAR(99),Column3 VARCHAR(99),Column4 VARCHAR(99))
    INSERT INTO T VALUES
    (1,'Value0','Value1','Value2','Value3','Value4'),
    (2,'Value0','Value1','Value2','Value3','Value4');
    DECLARE @columns VARCHAR(MAX)
    SELECT @columns=
    STUFF(
    SELECT ','+ COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='T' AND TABLE_SCHEMA='dbo' AND Column_name NOT IN('ID') FOR XML PATH('')
    ),1,1,'')
    DECLARE @Sql NVARCHAR(MAX)
    SET @Sql =
    'SELECT ID, UPT.col,UPT.val FROM T
    UNPIVOT
    (val FOR col IN('+@columns+')) AS UPT'
    EXEC sp_executeSQL @Sql
    DROP TABLE T
    If you have any feedback on our support, you can click
    here.
    Eric Zhang
    TechNet Community Support

  • 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

  • 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

  • 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
    Thanks

    If 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

  • 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,
    Serene

    Hello 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 Regards

    http://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

  • Oracle 10g Rows to column

    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.
    Thanks

      1  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 ?

  • Coverting a Row into Columns values

    Hi SQL Expert Friends,
    I have a row which contains 6 columns where I want that data to be shown in the form of columns as shown here:
    From:
    select item1, item2, item3, amt1, amt2, amt3 from item_table where sno=1; <----- returns 1 row as below
    ITEM1 ITEM2 ITEM3 AMT1 AMT2 AMT3
    AAA BBB CCC 10.00 20.00 15.00
    Data explanation: item1's (AAA) price is amt1 (10.00), item2's (BBB) price is amt2 (20.00) and item3's (CCC) price is amt3 (15.00). OK.
    Now I want that data to convert into columns as shown here:
    To:
    ITEMS AMT
    AAA 10.00
    BBB 20.00
    CCC 30.00
    Please help me friends, I want a SQL to display this data.
    I found one query which converts a row into columns, but this does not serve my requirement: [for your reference only]
    SQL> select substr( the_string
    , decode( level, 1, 1, instr(the_string,',',1,level-1)+1)
    , decode( instr(the_string,',',1,level), 0, length(the_string), instr(the_string,',',1,level) - decode( level, 1, 0, instr(the_string,',',1,level-1))-1)
    ) the_value
    from ( select (select item1||','||item2||','|| item3 from item_table where sno=1) ITEMS
    from DUAL)
    connect by level <= length(the_string)-length(replace(the_string,','))+1
    Thanks and REgards,
    Kiran

    Hi, Kirtan,
    kiran wrote:
    ... I want to learn this query, If you could explain me this how it works, then it will definitely helps me.If you don't understand a query that involves sub-queries, make sure you understand the sub-queries first. Run them separately, and study the results.
    In this case, the only sub-query is cntr. Run it separately, like this:
    WITH     cntr     AS
         SELECT     LEVEL     AS n
         FROM     dual
         CONNECT BY     LEVEL     <= 3
    SELECT    *
    FROM       cntr;Output:
    `        N
             1
             2
             3Why did I use the number 3 in "LEVEL <= 3"? Because each row will be unpivoted onto 3 rows. You could make this number 2, or 5, or 25 if that's how many rows you want in the output.
    Once you understand the sub-queries, try running the main query. Include the raw values of all columns that play any part in the output. For example:
    WITH     cntr     AS
         SELECT     LEVEL     AS n
         FROM     dual
         CONNECT BY     LEVEL     <= 3
    SELECT       CASE  cn.n
               WHEN  1  THEN  co.city1
               WHEN  2  THEN  co.city2
               WHEN  3  THEN  co.city3
           END          AS cities
    ,       CASE  cn.n
               WHEN  1  THEN  co.population1
               WHEN  2  THEN  co.population2
               WHEN  3  THEN  co.population3
           END          AS population
    ,       co.*          -- For testing/understanding only
    ,       cn.*          -- For testing/understanding only
    FROM             continent     co
    CROSS JOIN     cntr          cn
    WHERE     co.country     = 'America'
    ;Output:
    `            POPUL                                       POPUL  POPUL  POPUL
    CITIES       ATION COUNTRY  CITY1   CITY2       CITY3   ATION1 ATION2 ATION3  N
    Phoenix      20000 America  Phoenix Los Angeles Chicago  20000  15000  10000  1
    Los Angeles  15000 America  Phoenix Los Angeles Chicago  20000  15000  10000  2
    Chicago      10000 America  Phoenix Los Angeles Chicago  20000  15000  10000  3Why are there 3 rows of output? There are 3 rows in the cntr "table", and 3 rows in the continent table. Of these 3 * 3 = 9 rows, only the 3 rows shown above meet the condition in the WHERE clause. (Comment out the WHERE clause and try it again, if you want to see how that works.) Can you see how you get the output (the first 2 columns above) given all the data in the original columns? If not, ask a more specific question about the part you don't understand.

  • Rows to columns question

    Hi all,
    10.2.0.3 database.
    I need to convert MONTH ROW into columns. I tried few things with SYS_CONNECT_BY_PATH without any luck.
    Example:
    HOST     DB     TS     MONTH     SIZE_MB
    =========== === ====== ======= =======
    cltcrmspdb01     NP5     AIMD01     2005-08     4198
    cltcrmspdb01     NP5     AIMD01     2005-12     4627
    cltcrmspdb01     NP5     AIMD01     2005-05     2414
    cltcrmspdb01     NP5     AIMD01     2005-06     3966
    cltcrmspdb01     NP5     AIMD01     2006-04     5215
    cltcrmspdb01     NP5     AIMD01     2006-07     6288
    cltcrmspdb01     NP5     AIMD01     2006-05     5903
    cltcrmspdb01     NP5     AIMD01     2005-07     3977
    cltcrmspdb01     NP5     AIMD01     2006-06     6004
    cltcrmspdb01     NP5     AIMD01     2006-08     6312
    cltcrmspdb01     NP5     AIMD01     2005-11     4298
    cltcrmspdb01     NP5     AIMD01     2006-02     4591
    cltcrmspdb01     NP5     AIMD01     2005-09     3956
    cltcrmspdb01     NP5     AIMD01     2006-10     971
    cltcrmspdb01     NP5     AIMD01     2005-10     3850
    cltcrmspdb01     NP5     AIMD01     2006-01     4835
    cltcrmspdb01     NP5     AIMD01     2006-03     5429
    cltcrmspdb01     NP5     AIMD01     2006-09     6312
    HOST DB TS 2005-08 2005-09 2005-10 ...... 2006-09
    ============ === ====== ======= ======= ======= =======
    cltcrmspdb01 NP5 AIMD01 4198 4627 2414 6312
    Can somebody help me here. thanks in advance

    You need pivot query like this, (I didn't list all the months)
    select HOST, DB, TS,
               max( decode( month, '2005-08', SIZE, null ) ) 2005_08,
               max( decode( month, '2005-09', SIZE, null ) ) 2005_09,
               max( decode( month, '2005-10', SIZE, null ) ) 2005_10,
               max( decode( month, '2005-11', SIZE, null ) ) 2005_11
          from ( select HOST, DB, TS, MONTH, sum(SIZE_MB) SIZE
                   from yourtable
                  group by  HOST, DB, TS, MONTH)
         group by HOST, DB, TS

Maybe you are looking for

  • Work Center Mandatory  in PM Order

    Hi Experts, May i know how can i make Mandatory, both  Work center (Mn.wk.ctr) Under Person Responsible sub screen and the work center ( WkCtr/Plnt ) under first Operation sub screen  of the Header TAB in PM Order. Regards, Kavvya

  • Importing problems, HD from DV tape

    Hello! So I filmed on Canon Vixia, and then a Sony Handycam HDR-FX1000. Both instances I chose the HD record setting, and it was recorded onto a DV tape. Ive done it once before with the vixia, and couldnt get Final Cut Pro to recognize the footage o

  • Create Temporary Tables

    Hi, there. Can anybody tell me what's the syntax for the SQL statements to create temporary tables? I'm developing a shopping cart, and at the end of every purchase (checkout) I want to organize the items of the Session Bean Hash Table that contains

  • HT204382 How to convert VOB files into MP4 ? Tks

    Hi, anyone knows how to convert VOB files into MP4 ones ? Tks

  • SEM-BPS Real times issues

    Hi Gurus, I'm new to SEM-BPS Real times issues also some interview questions on SEM BPS. How we want to answer please forward to my email id: [email protected] thank regards Suresh