Search code examples
sqlsql-serverpivotsql-server-2014

Pivot Data Using a SQL Select Query


I need to pivot some data when doing a select query. I'm using SQL Server 2014. Here is the format of the original data.

    StudentID  | DocumentType  | PersonID
    ----------   -------------   --------
    00001           DocA           2222
    00001           DocB           2222
    00002           DocB           2222
    00002           DocA           3333
    00003           DocA           4444

And I want it to display like...

    StudentID |  DocumentTypeAPersonID | DocumentTypeBPersonID
    ---------    ---------------------   -----------------------
    00001               2222                     2222
    00002               3333                     2222
    00003               4444                     NULL

Sometimes a student will have both document types. Sometimes they will only have one. Not sure if the "missing" document type would show up as NULL or just blank in that field.


Solution

  • this way might save you some code

    SELECT  StudentID,
            DocumentTypeAPersonID = MAX(CASE WHEN DocumentType ='DocA' THEN PersonID END),
            DocumentTypeBPersonID = MAX(CASE WHEN DocumentType ='DocB' THEN PersonID END)
    FROM    MyTable
    GROUP BY StudentID