how to convert rows to columns

hi

i have a sample data like

patientno visit experimentdate

101 1 23-Dec-2004

101 2 23-Mar-2005

101 3 23-Jul-2005

102 1 23-Dec-2004

102 2 23-Mar-2005

102 3 23-Jul-2005

i want it to display like this

patientno visit1 visit1date visit2 visit2date visit3 visit3date

101 1 23-dec-2004 2 23-Mar-2005 3 23-Jul-2005

102 1 23-dec-2004 2 23-Mar-2005 3 23-Jul-2005

..please suggest how can we do it




Answer this question

how to convert rows to columns

  • deys

    Nope, not without using dynamic SQL. It isn't too hard, you just build the SELECT clause dynamically based on the data. In this post there is an example: http://forums.microsoft.com/MSDN/ShowPost.aspx PostID=488720&SiteID=1

  • HakanA

    Do you know if its possible to do this for a variable amount of Visits

  • David Scrutton

    select patientno
    ,visit1 = max(case when visit = 1 then 1 else null end)
    ,visit1date = max(case when visit = 1 then experimentdate else null end)
    ,visit2 = max(case when visit = 2 then 2 else null end)
    ,visit2date = max(case when visit = 2 then experimentdate else null end)
    ,visit3 = max(case when visit = 3 then 3 else null end)
    ,visit3date = max(case when visit = 3 then experimentdate else null end)
    from <tablename>
    group by patientno


  • how to convert rows to columns