Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9133429
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T08:29:16+00:00 2026-06-17T08:29:16+00:00

I need expert help. I thought I knew SQL pretty well, at least up

  • 0

I need expert help. I thought I knew SQL pretty well, at least up to this point. I’m working with SQL Server and need to build a query that lists each registered member and show each of the names of their guest(s) in separate columns instead of rows. Each member could have 0:N guests associated with each member. So, Here are my tables:

Member Table: memberID (PK), FName, LName, …

Guest Table: GuestID (PK), FName, LastName, …

Event Table: GuestID (PK), MemberID (PK),…

I am trying to build a query output like this:

MemberID | Member_FName | Member_LName | Guest1ID | Guest1_Fname | Guest2ID | Guest2_FName …

SAMPLE:

Member Table
MemberID | FName | LName
001        Frank   Smith   
002        Mary    Jane
003        John    Henry

Guest Table
GuestID | FName | LName
101       Steve   Smith
102       Peter   Smith
103       Mike    Jane

Event Table
MemberID | GuestID
001        101
001        102
002        103

OUTPUT:

MemberID | FName | LName| GuestID1 | FName1 | LName1 |GuestID2 | FName2 | LName2
001        Frank   Smith  101        Steve    Smith   102        Peter    Smith
002        Mary    Jane   103        Mike     Jane
003        John    Henry

Please let me know if I need to include other information.

thanks in advance!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T08:29:17+00:00Added an answer on June 17, 2026 at 8:29 am

    You can implement both the UNPIVOT and then the PIVOT functions to get the results. The UNPIVOT takes your columns and transforms the data into rows and the pivot takes the final result and turns it back into columns:

    select MemberID,
      memberfirst,
      memberlast,
      isNull(GuestId_1, '') GuestId_1, 
      isNull(fname_1, '') fname_1, 
      isNull(lname_1, '') lname_1,
      isNull(GuestId_2, '') GuestId_2, 
      isNull(fname_2, '') fname_2, 
      isNull(lname_2, '') lname_2
    from
    (
      select MemberID,
        memberfirst,
        memberlast,
        col+'_'+cast(rn as varchar(10)) col,
        value
      from
      (
        select m.MemberID,
          m.fname MemberFirst,
          m.lname MemberLast,
          isNull(cast(g.GuestID as varchar(5)), '') GuestId,
          isNull(g.fname, '') fname,
          isNull(g.lname, '') lname,
          row_number() over(partition by m.parentid order by g.guestid) rn
        from member m
        left join Event r
          on m.parentid = r.memberid
        left join guest g
          on r.guestid = g.guestid
      ) src
      unpivot
      (
        value
        for col in (GuestId, fname, lname)
      ) unpiv
    ) src1
    pivot
    (
      max(value)
      for col in (GuestId_1, fname_1, lname_1,
                  GuestId_2, fname_2, lname_2)
    ) piv
    

    See SQL Fiddle with Demo

    The above works great if you know the number of records ahead of time, but if not then you will want to use dynamic sql:

    DECLARE  @query  AS NVARCHAR(MAX),
        @colsPivot as  NVARCHAR(MAX),
        @colsPivotNull as  NVARCHAR(MAX)
    
    select @colsPivot = STUFF((SELECT  ',' 
                          + quotename(c.name +'_'+ cast(t.rn as varchar(10)))
                        from
                        (
                          select cast(row_number() over(partition by m.MemberID order by g.guestid) as varchar(50)) rn
                          from member m
                          left join Event r
                            on m.parentid = r.memberid
                          left join guest g
                            on r.guestid = g.guestid
                        ) t
                        cross apply sys.columns as C
                       where C.object_id = object_id('guest')
                       group by c.name, t.rn
                       order by t.rn
                FOR XML PATH(''), TYPE
                ).value('.', 'NVARCHAR(MAX)') 
            ,1,1,'')
    
    select @colsPivotNull = STUFF((SELECT  ', IsNull(' 
                          + quotename(c.name +'_'+ cast(t.rn as varchar(10)))+', '''') as '+c.name +'_'+ cast(t.rn as varchar(10))
                        from
                        (
                          select cast(row_number() over(partition by m.MemberID order by g.guestid) as varchar(50)) rn
                          from member m
                          left join Event r
                            on m.parentid = r.memberid
                          left join guest g
                            on r.guestid = g.guestid
                        ) t
                        cross apply sys.columns as C
                       where C.object_id = object_id('guest')
                       group by c.name, t.rn
                       order by t.rn
                FOR XML PATH(''), TYPE
                ).value('.', 'NVARCHAR(MAX)') 
            ,1,1,'')
    
    set @query 
      = 'select 
              MemberID,
              memberfirst,
              memberlast, '+@colsPivotNull+'
          from
          (
            select MemberID,
              memberfirst,
              memberlast,
              col+''_''+cast(rn as varchar(10)) col,
              value
            from 
            (
              select m.MemberID,
                m.fname MemberFirst,
                m.lname MemberLast,
                isNull(cast(g.GuestID as varchar(5)), '''') GuestId,
                isNull(g.fname, '''') fname,
                isNull(g.lname, '''') lname,
                row_number() over(partition by m.parentid order by g.guestid) rn
              from member m
              left join Event r
                on m.parentid = r.memberid
              left join guest g
                on r.guestid = g.guestid
            ) x
            unpivot
            (
             value
              for col in (GuestId, fname, lname)
            ) u
          ) x1
          pivot
          (
            max(value)
            for col in ('+ @colspivot +')
          ) p'
    
    exec(@query)
    

    See SQL Fiddle with Demo

    Both versions produce the same result:

    | MemberID | MEMBERFIRST | MEMBERLAST | GUESTID_1 | FNAME_1 | LNAME_1 | GUESTID_2 | FNAME_2 | LNAME_2 |
    -------------------------------------------------------------------------------------------------------
    |        1 |       Frank |      Smith |       101 |   Steve |   Smith |       102 |   Peter |   Smith |
    |        2 |        Mary |       Jane |       103 |    Mike |    Jane |           |         |         |
    |        3 |        John |      Henry |           |         |         |           |         |         |
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am not an expert in SQL therefore need your help. I have this
I need a regex expert to help out on this one. Examples I've found
I need to export data from several tables in SQL Server 2008 using SSMS.
I'm pretty new to Java, and I need to build up programming environments for
I am no expert in Flash, and I need some quick help here, without
I have spent several hours with this SQL problem, which I thought would be
I need to let my Rails app connect to a MS SQL Server database
Silverlight experts out there, I need some help. I used Deep Zoom Composer to
I am dealing with an issue and need some expert advice on to achieve
i need to convert a Utf-16BE in ISO-8859-1 in PHP (i'm not an expert

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.