SQL 102: A Useful Pivot

I don’t find myself pivoting data often but when I do I seem to always need to do the “complicated” pivot. You know, the one where you have a collection of unique values like email addresses where the value isn’t the column name but you want the 4 email addresses connected to one person in a single row rather than four rows. I can never remember how to do that so here is my personal internet bookmark for that code. Thanks to the late Robert Davis who gave the answer I needed back in 2015. Robert was a wonderful and generous contributor to the SQL Family his site is full of useful information and is still available here.

The solution is to add the categories you want as eventual columns to your result set before pivoting (it sounds simple enough but again then I can never remember it). So if you have say an account with multiple contacts:

This returns a list of results such as:

acctNo name email
1001 Susan susan@thesuze.com.edu
1001 Mark mark@thesuze.com.edu
1001 Aoife theboss@bagpipebattle.com.edu

The one simple trick is to create a value for each row that will be repeated it can be used as a column name when you pivot:

Simply repeat the structure of creating a valid column name (‘String’ + CAST(counter as VARCHAR)) and and you can include a pivot across as many different columns as need to be included. Our short list above now becomes:

acctNo Name1 Email1 Name2 Email2
1001 Susan susan@thesuze.com.edu Mark mark@thesuze.com.edu
1001 Aoife theboss@bagpipebattle.com.edu NULL NULL

Hopefully now in the future I’ll remember I wrote this and I won’t have to go searching for the solution (again).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s