Hi everyone,
Some time ago I was being asked if there was a way to denormalize a query result from a 1-to-many related tables/views.
Normally, you would get multiple row results set, in most cases. But, what was being asked was if there was a way to
grab the "many" part and transpose those into a single line with dynamic columns along with the rest of the data from the "1" part of the
query result.
At first, I thought that was going to be an easy one and PIVOT popped in my mind rather quickly. Don't get me wrong, it is
still an easy one, but, I was surprised that I was totally misunderstood the question and few minutes later I realized
that I should be on a different path.
PIVOT or the Matrix layouts in Report Builder 3.0 or in MSSQL Analysis Server the "behind the scene" functions
do provide that information to us quickly. So, why are we wasting our time on this? That was my question too!
This script may be helpful if one would like to pass a single parameter, wrap up and transpose the data and drop it on an
online or real-time page or frame for viewing purposes only, then that is great. The key is "real-time" information with the minimum cost.
You may want to alter this code and take it to the next level by make this more dynamic, from accepting TABLE name,
User Name, and even a JOIN statement along with the in question COLUMN and get your result-set dropped on screen.
Hope this may be helpful and useful and enjoy
JohnE
ACTIONS:
CREATE THE TEST SROUCE TABLES WITH DATA
DISPLAY THE INSERTED DATA FOR DEBUGGING
CREATE A STAGING TABLE AS A SOURCE TABLE
CREATE ANOTHER STAGING TABLE AS A TARGET FOR THE DENORMALIZED DATA COLUMNS
ALTER TARGET TABLE BY ADDING COLUMNS DYNAMICALLY
LOOP THRU THE DENORMALIZED COUMNS AND UPDATE THE CORRESPONDING COLUMNS