Mysql – Add data from rows to different columns if more than 1 row have a partial match

MySQLpivot

I tried to find a solution but do not find anything to add multiple columns from partially matching rows.

Data:(Maximum of 3 programs per person)

name     surname    program
Jan      Peters     program1
Jan      Peters     program2
Pete     Peters     program1
Jane     Smith      program3
Jane     Smith      program1
Jane     Smith      program2

Result needed:

name     surname    prog1       prog2      prog3
Jan      Peters     program1    program2
Pete     Peters     program1
Jane     Smith      program3    program1   program2

Even just pointing me into a direction would help.

Best Answer

Welcome.

Try this.

select name, surname, 
    max(prog1) as prog1, max(prog2) as prog2, max(prog3) as prog3 
 from
    (select name, surname, 
     if(program= 'program1', 'program1', '') as prog1, 
     if(program= 'program2', 'program2', '') as prog2, 
     if(program= 'program3', 'program3', '') as prog3 
    from db1) as tempdb
 group by name, surname;

This is possible only if the three program values are fixed / known prior to the code (itself).

For unknown values of program this is not possible directly. In such case, you may have to move them to another table / temporary table / view by multiplying columns and then assembling the same into one with more columns.