Search code examples
sqlsql-serversql-view

How to capture different values in the same column with a similar ID into one row with specific column indicators


I need to capture the yes or no answer to certain question codes into columns that serve as an indicator for each specific question code. The question codes are set values and for the sake of this example can only be 'A', 'B', or 'C'.

Any help would be greatly appreciated, I am looking forward to any answers you SQL gurus can think of!

Example Input Table:

    ID  Question Code   YesOrNo
    1         A             Yes
    1         B             No
    1         C             No
    2         A             No
    2         B             Yes
    2         C             Yes
    3         A             No
    3         B             No
    3         C             Yes

Desired Table/View:

    ID  A_Answer    B_Answer    C_Answer
    1   Yes         No          No
    2   No          Yes         Yes
    3   No          No          Yes

To clarify this is in SQL Server.


Solution

  • You can perform conditional aggregation:

    SELECT
        Id,
        A_Answer = MAX(CASE WHEN [Question Code] = 'A' THEN YesOrNo END),
        B_Answer = MAX(CASE WHEN [Question Code] = 'B' THEN YesOrNo END),
        C_Answer = MAX(CASE WHEN [Question Code] = 'C' THEN YesOrNo END)
    FROM Tbl
    GROUP BY Id;
    

    ONLINE DEMO