I have a simple problem when querying the SQL Server 2005 database. I have tables called Customer and Products (1->M). One customer has most 2 products. Instead of output as
CustomerName, ProductName …
I like to output as
CustomerName, Product1Name, Product2Name …
Could anybody help me?
Thanks!
Like others have said, you can use the PIVOT and UNPIVOT operators. Unfortunately, one of the problems with both PIVOT and UNPIVOT are that you need to know the values you will be pivoting on in advance or else use dynamic SQL.
It sounds like, in your case, you’re going to need to use dynamic SQL. To get this working well you’ll need to pull a list of the products being used in your query. If you were using the AdventureWorks database, your code would look like this:
Now that you have your columns, you can pull everything that you need pivot on with a dynamic query:
Of course, if you need to make sure you get decent values, you may have to duplicate the logic you’re using to build @columns and create an @coalesceColumns variable that will hold the code to COALESCE(col_name, 0) if you need that sort of thing in your query.