The following is my SELECT statement which pivots my data nicely.
My Data Looks like this:
col_a | col_b | col_c | col_d | Score
-------------------------------------
stuff | stuff | stuff | null | 5
stuff | stuff | stuff | title_a | 3
stuff | stuff | stuff | title_x | 4
My current Pivot statement looks like this:
SELECT `col_a`, `col_b`, `col_c`,
MAX(CASE `col_d` WHEN 'title_a' THEN `col_d` end) AS 'Title',
MAX(CASE `col_d` WHEN 'title_a' THEN `score` end) AS 'Score'
MAX(CASE `col_d` WHEN 'title_x' THEN `col_d` end) AS 'Title',
MAX(CASE `col_d` WHEN 'title_x' THEN `score` end) AS 'Score'
.....
This gives me the following results:
col_a | col_b | col_c | Title | Score | Title | Score
---------------------------------------------------------
stuff | stuff | stuff | title_a | 3 | title_x | 4
What I would like to do is check for more titles, however I only want to have four columns in the pivot. There will only ever be a maximum of 2 rows that require pivoting up to the record above. But col_d could contain any title.
For example I tried the following:
My Data now Looks like this:
col_a | col_b | col_c | col_d | Score
-------------------------------------
stuff | stuff | stuff | null | 5
stuff | stuff | stuff | title_a | 3
stuff | stuff | stuff | title_x | 4
stuff | stuff | stuff | null | 5
stuff | stuff | stuff | title_a | 3
stuff | stuff | stuff | title_bx | 4
My Pivot statement now looks like this:
SELECT `col_a`, `col_b`, `col_c`,
MAX(CASE `col_d` WHEN 'title_a' THEN `col_d` end) AS 'Title',
MAX(CASE `col_d` WHEN 'title_a' THEN `score` end) AS 'Score'
MAX(CASE `col_d` WHEN 'title_x' THEN `col_d` end) AS 'Title',
MAX(CASE `col_d` WHEN 'title_x' THEN `score` end) AS 'Score'
MAX(CASE `col_d` WHEN 'title_bx' THEN `col_d` end) AS 'Second Title',
MAX(CASE `col_d` WHEN 'title_bx' THEN `score` end) AS 'Score'
.....
So as you can see I tried checking for another title, but that just gave me six columns, 2 of them null because in this case the two rows contained title_a and title_bx, so the middle two columns where filled with null.
The output I would like from the above data is:
col_a | col_b | col_c | Title | Score | Title | Score
---------------------------------------------------------
stuff | stuff | stuff | title_a | 3 | title_x | 4
stuff | stuff | stuff | title_a | 3 | title_bx | 4
So my question is how can I check for multiple possible titles in col_d, and only have the 4 columns.
MAX(CASE WHEN 'col_d' IN('title1','title2','title3','title4') THEN 'col_d' END) AS my_col