pivot-unpivot

  • Hi,

    I have a data like this:

    select * from members where member_id = 1

    member_id  first_name last_name ssn

    ---------  ---------- --------- ---------

    1          Julia      Roberts   123456789

    I need to display data like this:

    member_id 1

    first_name Julia

    Last_name Roberts

    ssn           123456789

    What is the way to do this?

    Thanks,

     

  • I would return the data as one row and leave the presentation of the data to the application being used to display the data.

    If, however the data is being presented in a query tool such as Query Analyzer then you have to do something like:

    select 'member_id' ,  member_id

    from members where member_id = 1

    union all

    select 'first_name',  first_name

    from members where member_id = 1

    union all

    select 'last_name',  last_name

    from members where member_id = 1

    union all

    select 'ssn',  ssn

    from members where member_id = 1

    Also, it is a best practice that all table names be in the singular, MEMBER, not plural, MEMBERS, because one row of data represents a MEMBER.

  • You need to cast to the same datatype to get that working... Something like

    select 'member_id' ,  cast(member_id as varchar(100))

    from members where member_id = 1

    union all

    select 'first_name',  first_name

    from members where member_id = 1

    union all

    select 'last_name',  last_name

    from members where member_id = 1

    union all

    select 'ssn',  cast(ssn as varchar(100))

    from members where member_id = 1

  • Also, If you use Front End application, you can very well handle this there


    Madhivanan

    Failing to plan is Planning to fail

Viewing 4 posts - 1 through 3 (of 3 total)

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