First, I am a SQL noob, second if there is a better solution that can be implement in code later, I’d love to hear it. Also, the data is currently stored in MySQL but will eventually have to be ported to MSSQL so a cross DB solution would be best (if one exists).
Now, the problem, my simplified data looks like this:
[STYLES]
ID NAME
1 A Style
2 B Style
...
N N Style
[EQUIPMENT]
ID NAME
1 A Equipment
2 B Equipment
...
N N Equipment
[AVAILABILITY]
STYLE EQUIPMENT TYPE
1 1 Standard
1 2 Optional
2 1 Optional
... #items will be missing and represent not available
2 2 Standard
Now I need a table that looks like this:
[DESIRED_VIEW]
EQUIPMENT_NAME A_STYLE_TYPE B_STYLE_TYPE ... N_STYLE_TYPE
A Equipment Standard Optional ... NULL
B Equipment Optional NULL ... Standard
I have seen a number of simple pivot examples and they all rely on having a set number of columns. Is there a way to set up the view with a variable number of columns based on how many rows are in the STYLES table?
As a note, I am using Visual Studio to create the Data xsd and letting it auto-generate the table fill methods then displaying the info in WPF DataGrids so being able to bind directly to a view with the correct data would be ideal.
No – there is no way to write a query that has a dynamic number of columns.
Your choices are (in order of preference):
If you are comfortable with a maximum number of styles (it can be arbitrarily large, but finite), code your pivot would look like this:
When there is no availability type for a given style, you’ll get a
NULL.Also, you need to know the style ids and they need to be the same on all environemtns. If this is not the case (eg different in test/prod environments) you can change
a1.style = 1toa1.style = (select id from style where name = 'A Style')etc – it will still perform OK.