Convert 3X2 rows,columns to 1X6 row.columns

  • Hi

    Convert 3X2 rows,columns to 1X6 row.columns

    Phone +1 413 2220144

    Fax +1 413 2221144

    Email abcd@xyz.com

    I want to change above 3 rows into 1 row as below

    Phone +1 413 2220144,Fax +1 413 2221144,Email abcd@xyz.com

    Help

    Muralidaran r

  • You can do this by using the PIVOT function

    Check BOL for syntax.

  • Something like this?

    CREATE TABLE #ContactDetails (ContactID INT, ContactMethod VARCHAR(5), ContactDetail VARCHAR(30))

    INSERT INTO #ContactDetails (ContactID, ContactMethod, ContactDetail)

    SELECT 1, 'Phone', '+1 413 2220144' UNION ALL

    SELECT 1, 'Fax', '+1 413 2221144' UNION ALL

    SELECT 1, 'Email', 'abcd@xyz.com' UNION ALL

    SELECT 2, 'Phone', '+1 413 2220145' UNION ALL

    SELECT 2, 'Fax', '+1 413 2221145' UNION ALL

    SELECT 2, 'Email', 'efgh@xyz.com'

    SELECT ContactID,

    MAX(CASE ContactMethod WHEN 'Phone' THEN ContactDetail END) AS 'PHONE',

    MAX(CASE ContactMethod WHEN 'Fax' THEN ContactDetail END) AS 'FAX',

    MAX(CASE ContactMethod WHEN 'Email' THEN ContactDetail END) AS 'EMAIL'

    FROM #ContactDetails

    GROUP BY ContactID

    “Write the query the simplest way. If through testing it becomes clear that the performance is inadequate, consider alternative query forms.” - Gail Shaw

    For fast, accurate and documented assistance in answering your questions, please read this article.
    Understanding and using APPLY, (I) and (II) Paul White
    Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden

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

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