Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL : How to convert multiple row to single row? in mysql

Tags:

mysql

pivot

I want to convert multiple rows to a single row, based on week. It should look like the following. Can any one help me?

id      |   Weight   |  Created   |
 1      |    120     | 02-04-2012 |
 2      |    110     | 09-04-2012 |
 1      |    100     | 16-04-2012 |
 1      |    130     | 23-04-2012 |
 2      |    140     | 30-04-2012 |
 3      |    150     | 07-05-2012 |

Result should look like this:

id      |   Weight_week1  | Weight_week2  |  weight_week3  | weight_week4  |
 1      |     120         |     100       |      130       |               |
 2      |     110         |     140       |                |               |
 3      |     150         |               |                |               |

Thanks in advance.

like image 563
san Avatar asked Dec 06 '25 15:12

san


1 Answers

if this a single table then

SELECT GROUP_CONCAT(weight) as Weight,
        WEEK(Created) as Week
Group by Week(Created)

This will give you a row each having week id and comma seperated whights

like image 111
Muhammad Raheel Avatar answered Dec 08 '25 23:12

Muhammad Raheel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!