Aaron Bertrand’s speaking my language:
I’ve written about
UNPIVOT
before – see Use SQL Server’s UNPIVOT operator to help normalize output and Use SQL Server’s UNPIVOT operator to dynamically normalize output. It’s a powerful language feature that lets you flip results sideways, sort of like the opposite ofPIVOT
. This is great if you have columns likePhone1
andPhone2
but want to collapse them into one column. One of the challenges is that if you have other columns you also want to collapse similarly, likeEmail1
andEmail2
, you need to add an additionalUNPIVOT
operator or use a different approach. Is there a way to do this in a less complicated way?
Click through for the answer. And a free Curated SQL protip: if you ever want linked here, write an article about a good use case for the APPLY
operator. I’m a sucker for those.