0

I have simplified my data to something much like the following:

+---------+-----+--------+
| item  | type  | color  |
+-------+-------+--------+
|   1   |   A   | red    |
|   1   |   B   | blue   |
|   2   |   A   | orange |
|   2   |   B   | pink   |
|   2   |   C   | blue   |
|   3   |   B   | yellow |
+---------+-----+--------+

The number of 'type' per item is variable, therefore, I need a MySQL pivot solution that is dynamic and can handle any number of types. The following is the kind of result set I need to return from the MySQL query. As you can see, I do not need a summary calculation.

+---------+------+--------+--------+
| item  |   A    |   B    |   C    |
+-------+--------+--------+--------+
|   1   | red    | blue   |        | 
|   2   | orange | pink   | blue   |
|   3   |        | yellow |        |
+-------+--------+--------+--------+

I suspect the solution may involve the use of a MySQL procedure?

1

2 Answers 2

0
select item, min(A), min(B), min(C) from (
    select item, 
        case when type = 'A' then color end as 'A',
        case when type = 'B' then color end as 'B',
        case when type = 'C' then color end as 'C'
    from color
) as tbl
group by item
Sign up to request clarification or add additional context in comments.

1 Comment

this works if the number of possible types is fixed, however the number of types may be fewer or greater. So I need the mysql statement to dynamically adapt to the data. This is why I suspect I may need a mysql procedure to build the case statements?
0

You are "pivoting". In my blog, I provide a generic stored procedure to generate the SELECT statement for you.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.