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
Thanks

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

Similar Messages

  • Dynamic SQL rows to column

    I have a table something like
                                  WHERE    IN
                                  Age           18
                                  Year           2012,2013
                                  Color         Blue
    --etc
                                  I would like to create a dynamic statement base on this table
                                  Dyanmic SQL:
                                  WHERE AGE IN (18) and Year IN (2012,2013) and Color IN (‘Blue’)
    I am using SQL server 2008 R2. How can I do this using XML path or something

    Here you go:
    DECLARE @tbl TABLE ([WHERE]   sysname NOT NULL,
                         [IN]     nvarchar(200))
    INSERT @tbl([WHERE], [IN])
       VALUES ('Age', '18'), ('Year', '2012,2013'), ('Colour', 'Blue,Yellow')
    DECLARE @where nvarchar(MAX)
    SELECT @where =
       (SELECT [WHERE] + ' IN (' +
                CASE WHEN [IN] LIKE '%[^0-9,]%'
                     THEN replace(quotename([IN], ''''), ',', ''',''')
                     ELSE [IN]
                END + ') AND '
        FROM   @tbl
        FOR XML PATH(''), TYPE).value('.', 'nvarchar(MAX)') + ' 1 = 1'
    SELECT @where
    However, this is somewhat brittle. I'm assuming that a comma is a list separator; never part of a value searched for. I'm also assume that as long as a value is digits only, it is numeric, else it is a string. This would fail if there is a date value
    on the form YYYYMMDD.
    Probably you should store metadata somwhere, so that you know the data type of a column.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • 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

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

  • Rows to columns with MAX(DECODE)

    Hi Guys,
    I got a problem when transposing my rows to columns again.
    this select gets me the unique combination of a translation in 3 languages.
    what makes it unique is the combination of table_id, table_name,column_name.
    select TABLE_ID,TABLE_NAME, COLUMN_NAME,Lang,Trans_TEXT from T_translations where TABLE_NAME='table1' and COLUMN_NAME ='column1' and Table_id='231441';
    gives me three rows with the same table_id_table_name and column_name, what differs is the language each time and the text.
    I guess the unique-making columns also have to be in the partition by cause:
    SELECT TABLE_PK1,
    MAX(DECODE ( rn , 1, Trans_TEXT)) English,
    MAX(DECODE ( rn , 2, Trans_TEXT)) Chinese,
    MAX(DECODE ( rn , 3, Trans_TEXT)) Russian
    FROM
    (SELECT TABLE_ID,Table_Name,Column_Name Trans_TEXT,
    row_number() OVER ( partition by TABLE_ID,Table_Name,Column_Name order by rownum) rn
    FROM T_translations where Trans_TEXT is not null)
    group by TABLE_id,Table_Name,Column_Name
    The problem is that everything comes out scrabled. all the translated text is mixed up. English text
    is in column Chinese and Russian is in,.... I cant see a logic.
    Does someone have an idea?

    Hi,
    Instead of this
    row_number() OVER ( partition by TABLE_ID,Table_Name,Column_Name order by rownum) rnselect LANG and do your decode on that.
    Something like (No need for the subselect)
    SELECT   table_id,
             MAX (DECODE (lang, 'ENGLISH', trans_text)) english,
             MAX (DECODE (lang, 'CHINESE', trans_text)) chinese,
             MAX (DECODE (lang, 'RUSSIAN', trans_text)) russian
    FROM  t_translations
    WHERE  lang IN ('RUSSIAN', 'ENGLISH', 'CHINESE')
    GROUP BY table_id,
             table_name,
             column_name;Regards
    Peter

  • 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/2005

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

  • Can anybody help....SQL to display row as column and column as rows

    Can anybody help in writing a SQL to display row as column and column as rows?
    Thanks

    check this link:
    Re: Creating Views - from rows to a new column?

  • How to Transpose a Row into a Column ? (URGENT)

    I am trying to transpose a row into a column and please pay attention "Just one row of a table into a column of another table". Unlike Excel, in Numbers there is no easy way to transpose data but this is a bit urgent to me, any help would be appreciated!!!!

    Dear Friend,
    I have been looking for an answer the whole day and have performed every possible solution in the index, transpose, lookup and all the other recommended functions, none of them have worked for me in this case. I have gone through more than 20 posts on the discussion board but all of them were useless. I havent tried your method yet but although I appreciate your help and time, I dont remember forcing you or anyone else to help me, I just looked at posting my question  as an option to avoid writing long scripts for such a basic function that is easily available on excel under the special paste option.
    I thank you very much in advance for the advice.
    PS. I tried it and with a couple of modifications it worked, thank you very much for making my day
    Message was edited by: cool3pehr

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

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

  • Transpose of columns to rows (unpivoting) and not rows to columns

    Hi,
    I am right now using oracle 10g. I HAVE the following specification. Here I specified only 5 columns.
    We have upto 200 columns.
    TRANS_ID      PORTFILIO_NUM     TICKER          PRICE     NUM_SHARES ........................................
    2     100     MO      25.00     100 ........................................
    3     100     MCD          31.50     100 ........................................
    I want the above to be transformed into the following output .
    TRANS_ID TYPE VALUE
    2 PORTFILIO_NUM 100
    2 TICKER MO
    2 PRICE 25.00
    2 NUM_SHARES 100.
    I don't want to use case/decode function by hard coding the 200 columns.
    Can anyone provide me a good way (mostly dynamic way) of doing this?
    I searched the whole forum and also other forums. Everywhere I could find
    rows to columns / columns to rows where the column names have been hardcoded.
    I want a dynamic way of doing it. Let me know if u need any other inputs.
    DDL :
    CREATE TABLE PORT_TRANS
    TRANS_ID VARCHAR2(100 BYTE),
    PORTFILIO_NUM VARCHAR2(100 BYTE),
    TICKER VARCHAR2(100 BYTE),
    PRICE VARCHAR2(100 BYTE),
    NUM_SHARES VARCHAR2(100 BYTE)
    INSERT INTO PORT_TRANS (TRANS_ID,PORTFILIO_NUM,TICKER,PRICE,NUM_SHARES)
    VALUES('2','100','MO','25.00','100');
    INSERT INTO PORT_TRANS (TRANS_ID,PORTFILIO_NUM,TICKER,PRICE,NUM_SHARES)
    VALUES('3,'100','MCD','31.50','100');
    COMMIT;
    Thanks,
    Priya.

    Hi,
    What you're trying to write is something like this:
    WITH     cntr     AS
         SELECT     LEVEL     AS n
         FROM     dual
         CONNECT BY     LEVEL     <= 4
    SELECT     p.trans_id
    ,     CASE
              WHEN  c.n     <= 2
              THEN
                   CASE     c.n
                        WHEN 1     THEN 'PORTFILIO_NUM'
                        WHEN 2     THEN 'TICKER'
                   END
              ELSE
                   CASE     c.n
                        WHEN 3     THEN 'PRICE'
                        WHEN 4     THEN 'NUM_SHARES'
                   END
         END     AS type
    ,     CASE
              WHEN  c.n     <= 2
              THEN
                   CASE     c.n
                        WHEN 1     THEN p.PORTFILIO_NUM
                        WHEN 2     THEN p.TICKER
                   END
              ELSE
                   CASE     c.n
                        WHEN 3     THEN p.PRICE
                        WHEN 4     THEN p.NUM_SHARES
                   END
         END     AS value
    FROM          port_trans     p
    CROSS JOIN     cntr          c
    ORDER BY     p.trans_id
    ,          c.n
    ;I wrote this as if CASE could only handle 2 choices, rather than 128, just to show how to nest CASE expressions.
    What you have to do is write the CASE expressions, based on the contents of all_tab_columns.
    In your sample data, all of the columns are VARCHAR2 (another design flaw). If you have any columns of other types, use TO_CHAR to convert them to VARCHAR2; that is, the final code to be run will have something like:
    ...                    WHEN 4     THEN TO_CHAR (p.NUM_SHARES)If I had to do this, I might run several queries on all_tab_columns, each producing one script, containing just a fragment of the query.
    To run the whole thing, I would hard-code a main query like this
    WITH     cntr     AS
         SELECT     LEVEL     AS n
         FROM     dual
         CONNECT BY     LEVEL     <=
                        @num_columns.sql
    SELECT     p.trans_id
    ,     CASE
              @type.sql
         END     AS type
    ,     CASE
              @value.sql
         END     AS value
    FROM          port_trans     p
    CROSS JOIN     cntr          c
    ORDER BY     p.trans_id
    ,          c.n
    ;As with any coidng, start small and take baby steps. Maybe the first step would just be to write num_columns.sql, which just contains the number 4. When you can do that, hard-code the CONNECT BY query, calling num_columns.sql.
    Good luck!

  • Rows to columns in sql

    Hi,
    How can i convert rows to column in sql
    I have table with the two columns child_table_name and parent_table_name as below. How can convert the below table to the expected output. show all the child and corresponding parent_table in one row. Please help to write sql
    Child_table_Name   Parent_Table_name
    abc                           bbb
    abc                           aaa
    def                             ccc
    def                              ttt                          
    Expected Output
    abc                 bbb              aaa
    def                  ccc              ttt
    Thanks,
    Ch

    Hi,
    That's called a Pivot, and here's one way to do it:
    WITH    got_r_num    AS
        SELECT  child_table_name
        ,       parent_table_name
        ,       ROW_NUMBER () OVER ( PARTITION BY  child_table_name
                                     ORDER BY      parent_table_name
                                   )  AS r_num
        FROM    table_x
    SELECT    *
    FROM      got_r_num
    PIVOT     (   MAX (parent_table_name)
                  FOR  r_num  IN  ( 1   AS parent_1
                                  , 2   AS parent_2
                                  , 3   AS parent_3
    The forum FAQ has a page devoted to pivots:
    https://forums.oracle.com/message/9362005#9362005
    The query above can show up to 3 parents per child.  If you know you'll never have more than 2 (as in your message) then you don't need the line that defines parent_3.  On the other hand, if you might need more than 3 parents, you can add as many more as you need.
    I hope this answers your question.
    If not, post  a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all tables involved, and also post the results you want from that data.
    Point out where the statement above is getting the wrong results, and explain, using specific examples, how you get the right results from the given data in those places.  Remember that there is no built-in order to the rows in a table, so if your explanationuses words like "first" or "latest", define what they mean in terms of the data in your table.
    Always say which version of Oracle you're using (e.g., 11.2.0.2.0).
    See the forum FAQ: https://forums.oracle.com/message/9362002

  • Converting rows to columns using t-sql

    Hi All,
    I have a table with 3 columns, let say ID1 , ID2, Flag
    My Source data looks like this..
    ID1    ID2       Flag
    1         1            0
    1         2            0
    1         3            0
    2         7            0
    2         8            1
    2         9            0
    4         5            0
    Now My output should look like this..
    ID1     Newcol1     NewFlag1     Newcol2     NewFlag2   Newcol3    NewFlag3
    1           1                    0                  
     2                   0                3                
    0
    2           7                    0               
        8                   1                9                
    0
    4           5                    0                  
     null               null            null              null
    Basically I want to convert rows to columns and to get above output I need t-SQL query.
    Thanks in advance
    RH
    sql

    You can do it by this query:
    declare @table table ( ID1 int, ID2 int, Flag int)
    insert @table values ( 1,1,0 ),( 1,2,0 ),( 1,3,0 ),( 2,7,0 ),( 2,8,1 ),( 2,9,0 ),( 4,5,0 )
    WITH cte1
    AS ( SELECT Id1 ,
    ROW_NUMBER() over (partition by ID1 order by ID1 ) as Sequence ,
    ID2 ,
    Flag
    FROM @table
    cte2
    AS ( SELECT Id1 ,
    ColumnTitle + LTRIM(RTRIM(STR(Sequence))) AS ColumnTitle ,
    ColumnData
    FROM cte1 UNPIVOT ( ColumnData FOR ColumnTitle IN ( [ID2], [Flag] ) ) AS UP
    SELECT Id1 ,
    [ID21] FirstID2 ,
    [Flag1] FirstFlag ,
    [ID22] SecondID2 ,
    [Flag2] SecondFlag ,
    [ID23] ThirdID2 ,
    [Flag3] ThirdFlag
    FROM cte2 PIVOT ( MAX(ColumnData) FOR ColumnTitle IN ( [ID21],
    [Flag1],
    [ID22],
    [Flag2],
    [ID23],
    [Flag3] ) ) PV
    If you want to know more detail, please visit my old article about this method:
    T-SQL: PIVOT Ordered pair Columns
    T-SQL e-book by TechNet Wiki Community
    My Blog
    My Articles

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

    Save youe file to transpose as a csv and in the header row of your file for the columns you want to transpose you need to put some soer of a tag before the column name (ie your colum header was for a period budget will be something lie 2011001:ZFIBDD)
    1. You will need to create a new apd process (rsanwb)
    2. Insert a "Read from Data File" data source object and map it file (,csv)
    3. insert a transpose object into your apd process (middle row 4th one over in the transformations section)
    4. under the definition tab in the transformation object select all the columns that are to be transposed into rows and move them to the transformed area, the grouping fields section should contain the rows that you want to now be columns
    5.under the transformation tab enter in the seperator you selected  under the Field Name/Infoobject area (ie. ZFIBDD)
    6. under the details tab  you need to enter in all the fields to be transformed and tner the transposition field (ie ZFIBDD)
    7. Then you can insert a set of transformations and a DSO and link the newly transposed fields into that.
    hope that helps

  • How to convert rows to columns in sql server 2008

    How to convert rows to columns in sql server 2008 using the GROUP BY function? (only one query allowed)

    Lookup the Pivot transformation. From BOL:
    The Pivot transformation makes a normalized data set into a less normalized
    but more compact version by pivoting the input data on a column value. For
    example, a normalized Orders data set that lists customer name, product, and quantity purchased typically has multiple rows for any customer who purchased multiple products, with each row for that customer showing order
    details for a different product. By pivoting the data set on the product column, the Pivot transformation can output a data set with a
    single row per customer. That single row lists all the purchases by the customer, with the product names shown as column names, and the quantity shown as a value in the product column. Because not every customer purchases every product, many columns may contain
    null values.
    When a dataset is pivoted, input columns perform different roles in the pivoting process. A column can participate in the following ways:
    The column is passed through unchanged to the output. Because many input rows
    can result only in one output row, the transformation copies only the first
    input value for the column.
    The column acts as the key or part of the key that identifies a set of
    records.
    The column defines the pivot. The values in this column are associated with
    columns in the pivoted dataset.
    The column contains values that are placed in the columns that the pivot
    creates.
    Paul

Maybe you are looking for

  • Smart object & timeline

    In PS6 I'm having trouble synchonising an animated drummer [as a smart object] with the audio track from the original clip I've drawn inlayers - because, when I go to the smart object edit file, the audio isn't there. I tried to copy the track and pa

  • Scheduling agreement  does not get updated (though in valid period)

    Hi, Once I change the setting of document type LPA from Time dependent conditiopns to Time independent conditions, how can I convert existing scheduling agreements that have been already created to time independent settings? Is it posible? Regards, A

  • Need a way to manage 600  iphones and install apps remotely. HELP Please

    Guys, We have 608 iPhone in our organisation and we are looking into a way to manage/ Track (when Lost) and deploy apps to these devices from one central server. Any Ideas on the best way to manage this task? Dave

  • RFC User for satellite systems

    Hello Gurus, I just wanted to ask about one issue. We are a SAP partner and using Solution Manager in VARs scenario. There are many systems of our customers connected to our Solution Manager.. Now I want to ask about RFC user(s). As I see, in our Sol

  • URL does not resolve correctly

    Hi, When calling portal30.wwsec_app_priv.logout?p_done_url=url/page/<pagename> under R1 the re-direct works fine. Have modified code for R2 to be portal.wwsec_app_priv.logout?p_done_url=url/page/<pagegroupname>/<pagename> - now I get "page could not