Someone is trying to extract data from SQL Server into a format that is more Excel-manipulable. Here is sample data from SQL Server. Note: I changed the text from our industry-specific stuff to a car analogy, but that's all:
Table: Products
products_id | products_model
============================
100 | Saturn Vue
200 | Toyota Prius
300 | Ford Focus
Table: Categories
categories_id | categories_name
===============================
1 | Leather Seats
2 | Heated Seats
3 | Tapedeck
4 | Heater
5 | Hybrid
6 | Sunroof
7 | Cruise Control
Table: Products_Categories
products_id | categories_id
===========================
100 | 3
200 | 1
200 | 4
200 | 5
300 | 4
300 | 7
This is what they want the results/output to look like:
products_id | products_model | Leather Seats | Heated Seats | Tapedeck | Heater | Hybrid | Sunroof | Cruise Control
===================================================================================================================
100 | Saturn Vue | N | N | Y | N | N | N | N
200 | Toyota Pruis | Y | N | N | Y | Y | N | N
300 | Ford Focus | N | N | N | Y | N | N | Y
I can't figure out how to get it to work. I tried playing with PIVOT, but it got too complex for me. I'll accept any type of solution so long as the final result looks like the one above.
The create script is in SQLFiddle.
You can use the
PIVOT
function to transform this data:See SQL Fiddle with Demo.
If the
categories_name
values are unknown or not fixed, then you can use dynamic sql:See SQL Fiddle with Demo
The result of both queries is:
easier to understand version