Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transpose MySQL rows and repeat column headers?

I have a mysql table that looks like:

id  group_id   item_code  item_label  item_detail    item_score
1   10         BLU123     Blue 123    Blah blah 123  3
2   10         BLU124     Blue 124    Blah blah 124  6
3   10         BLU125     Blue 125    Blah blah 125  2

Is there any sql statement that will output the table as:

group_id   item_code1  item_label1  item_detail1    item_score1  item_code2  item_label2  item_detail2    item_score2  item_code3  item_label3  item_detail3    item_score3
10         BLU123      Blue 123     Blah blah 123   3            BLU124      Blue 124     Blah blah 124   6            BLU125      Blue 125     Blah blah 125   2

Thanks all!

like image 213
user1950195 Avatar asked Jan 05 '13 01:01

user1950195


People also ask

How do I transpose rows to columns in MySQL?

If you want to transpose only select row values as columns, you can add WHERE clause in your 1st select GROUP_CONCAT statement. If you want to filter rows in your final pivot table, you can add the WHERE clause in your SET statement.

How do I PIVOT columns to rows in MySQL?

Unfortunately, MySQL does not have PIVOT function, so in order to rotate data from rows into columns you will have to use a CASE expression along with an aggregate function.

HOW CAN GET row values as column names in MySQL?

If you don't know the column names before hand, or want to display row values as columns in MySQL dynamically, you can create dynamic pivot tables in MySQL using GROUP_CONCAT function, as shown below. GROUP_CONCAT allows you to concatenate field_key values from multiple rows into a single string.


1 Answers

For what you want, to select all rows to insert into one row in Excel. Have as many rows in your table as you like.

SELECT 
    CONCAT(
        group_id,',', GROUP_CONCAT( 
            CONCAT_WS(',', item_code, item_label, item_detail, item_score) 
        )
    )
FROM thetable

Returns CSV:

10,BLU123,Blue 123,Blah blah 123,3,BLU124,Blue 124,Blah blah 124,6,BLU125,Blue 125,Blah blah 125,2
like image 58
Popnoodles Avatar answered Oct 06 '22 02:10

Popnoodles