Transpose a row into columns with MySQL without using UNIONS?

前端 未结 2 1555
暗喜
暗喜 2020-12-20 05:44

I have a table that is similar to the following below:

       id |        cat |         one_above |        top_level | 
        0    \'printers\'          \'         


        
2条回答
  •  隐瞒了意图╮
    2020-12-20 06:27

    I got this out of the book The Art of SQL, pages 284-286:

    Let's say your table name is foo.

    First, create a table called pivot:

    CREATE Table pivot (
      count int
    );
    

    Insert into that tables as many rows as there are columns that you want to pivot in foo. Since you have three columns in foo that you want to pivot, create three rows in the pivot table:

    insert into pivot values (1);
    insert into pivot values (2);
    insert into pivot values (3);
    

    Now do a Cartesian join between foo and pivot, using a CASE to select the correct column based on the count:

    SELECT foo.id, Case pivot.count
      When 1 Then cat
      When 2 Then one_above
      When 3 Then top_level
    End Case
    FROM foo JOIN pivot;
    

    This should give you what you want.

提交回复
热议问题