I have the following sample data:
Id Name Category
-----------------------
1 Joe A
2 Joe B
3 Joe D
4 Mary A
5 Mary C
6 Mary D
I would like to show the categories a person belongs to like so:
Name CategoryA CategoryB CategoryC CategoryD
--------------------------------------------------
Joe X X X
Mary X X X
1's and 0's could be used in place of X's and blanks.
This smells like a PIVOT question to me.
There are several ways that you can transform the data. Some use an aggregate function and others don't. But even though you are pivoting a string you can still apply an aggregate.
Aggregate with CASE:
See SQL Fiddle with Demo
Static Pivot:
You can still use the
PIVOT
function to transform the data even though the values are strings. If you have a known number of categories, then you can hard-code the query:See SQL Fiddle with Demo.
Dynamic Pivot:
If you have an unknown number of categories, then you can use dynamic SQL:
See SQL Fiddle with Demo.
Multiple Joins:
See SQL Fiddle with Demo
All queries will give the result: