I've got a table in database that looks like this:
CustomerId Attribute Value
================================
30 Name John
30 Surname Smith
30 Phone 555123456
to make some use of the data I need to make it look sth. like this:
CustomerId Name Surname Phone
======================================
30 John Smith 555123456
I know I can create stored procedure or table-valued function that will do it for me, but I'm wondering what would be the best choice here? Maybe I can do it with some clever sql select query only?
If this is SQL Server 2005 or later, you can use
PIVOT
:Or a solution that does not use
PIVOT
:Given the following scenario:
running this insert
shall output this:
Where:
from:
select distinct CustomerID from vertical
brings all customers that have at least one attribute.each left join returns the corresponding value for each attribute.
left join was used to ensure that the customer row will be inserted even if the customer is missing some attributes in which case NULL will be inserted.
source table named vertical is the one with the attribute values
target table named horizontal is your desired output
Sounds like you need to PIVOT. You should read the following article to learn how to do that:
PIVOT functionality in SQL Server