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!
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With