Search code examples
sqlsql-serversubqueryqsqlquery

converting rows into columns in sql


How to query to get following result...?!!

table 1:

MainID col1 col2

1       qq    qq

2       qq    qq

3       qq    qq

4       qq    qq

5       qq    qq

table 2

MainID      lineNo      Text

1           1           price

1           2           name

1           3           date

2           1           price

2           2           name

2           3           date

i need a query to result like

MainId     Col1    col2     price   name    date

1           qq      qq      price   name    date

2           qq      qq      price   name    date

This requires 3 different columns to be made on 3 different conditions for a MainID ; forming a single row.


Solution

  • You should be able to do the following by joining on multiple embedded queries:

    Select 
          table1.MainID, table1.col1, table1.col2, q1.price, q2.name, q3.date
    from 
    table1 
    left outer join (select 
                     MainID, lineNo, Text as price 
                     from 
                     table2) q1 on table1.MainID = q1.MainID
    left outer join (select 
                     MainID, lineNo, Text as name 
                     from table2) q2 on table1.MainID = q2.MainID
    left outer join (select 
                     MainID, lineNo, Text as date 
                     from table2) q3 on table1.MainID = q3.MainID