Column to row

  • Is there a simple way to show columns as rows in a table.

    I got a table looks like this

    pk(Auto)    ID      Dataname     Data

    1           111     Name         abc

    2           111     Address      123, street

    3           111     City         Atlanta

    4           222     Name         efg

    5           222     Address      456, somewhere

    6           333     Name         xyz

    I want to show end user a report like below

    ID    Name      Address           City

    111   abc       123, street       Atlanta

    222   efg       456, somewhere

    333   xyz

    Can someone show me how to show this.

    Thanks

    ash

  • Depending on your reporting software, this may be easier to re-organize with it. What are you using to generate reports?

    K. Brian Kelley
    @kbriankelley

  • Iam using SQL reporting services, but I need SQL query to create this as view.

     

    Thank you

    ash

  • You can join table to itself

    SELECT MT1.ID, MT1.Data as Name, MT2.Data as Address, MT3.Data as City

    FROM MyTable MT1

    inner join MyTable MT2 on MT1.ID = MT2.ID

    inner join MyTable MT3 on MT2.ID = MT3.ID

    where MT1.Dataname = 'Name'

            and MT2.Dataname = 'Address'

            and MT3.Dataname = 'City'

    _____________
    Code for TallyGenerator

  • Thanks Sergiy,

    Your solution is great, but each id can have upto 20 to 30 records means that many different fields like name and address.

    I'm thinking about something dynamic to get all unique datanames for each id and show the data for each record.

    Thanks

    ash

  • One more thing I forgot to mention, all Id's dont have constant number of records or fields.

    One id can have 5 records another can have 20 records, so I need to show remaining 15 fields as null fields for id with 5 records.

    Thanks

    ash

  • assuming you have to analyze the query results given, dynamic sql is your friend. there may be a better way to get the numbers you want if you posted the query that gives you the numbers above.

Viewing 7 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic. Login to reply