Integrating multiple rows into one row in sql

I want to integrate an unspecified number of rows into one row in sql. For this I need a sql query.

My opinion:

service_id  title   value
----------  -----   -----
1              A    10
1              B    20
1              C    40
2              A    15
2              B    72
2              C    70
.              D     .
.              F     .
.              .     .

The result I was expecting was:

service_id  A   B   C   D F ..
----------  -   -   -   - - ---
1          10   20  40  . . .
2          15   72  70  . . .
.
.

The number of fields is unknown (A, B, C, ...)

+4
source share
1 answer

If you want to use this in MySQL, you can use this

select service_id  , group_concat(`titlevalue` separator ',') as `your_fild_name` from ( select id, concat(`title`, ':',  group_concat(`value` separator ',')) as `titlevalue` from your_table_name group by id, `titlevalue`) tbl group by service_id  ;
+1
source

Source: https://habr.com/ru/post/1672429/


All Articles