Skip to content
Advertisement

Dynamic TSQL Pivot without aggregate function

I have a table like this (‘ExternalPersonRelationTable’)

PersonId SubjectCode
4187 3
4187 278
4429 3
4429 4
4463 99
4464 174
4464 175

I want to rotate the data so that every person in the table gets a column and a TRUE/FALSE value for each subject code, i.e. a table like this:

Code 4187 4429 4463 4464
3 TRUE TRUE FALSE FALSE
4 FALSE TRUE FALSE FALSE
99 FALSE FALSE TRUE FALSE
174 FALSE FALSE FALSE TRUE
175 FALSE FALSE FALSE TRUE

I gather this is a problem I should solve using PIVOT and dynamic SQL, but I’m afraid my experience is limited to using CTE’s and simple JOINs, so I am having a hard time PIVOTing the data, never mind dynamically naming the resulting columns.

The SubjectCode and PersonId will eventually be joined to other tables in order to fetch their real values, but for the example I think they are unnecessary.

How do I solve this?

Advertisement

Answer

Sample data

Solution

Start with a (limited) static version of the pivot query as a reference.

Identify the dynamic parts and construct (and validate) those.

Merge the dynamic parts in the final query (and validate during development phase).

Run the dynamic query.

Result

Fiddle to see things in action.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement