DKprojektai DKprojektai - 1 month ago 8
MySQL Question

MySQL row into number of columns and sum

could somebody help with sql.

I have table with records

ID | Car_num | Service | Price

1 | 001 | shower | 10

2 | 002 | TV | 5

3 | 001 | TV | 5

How to write SQL query in order to get output

ID |Car_num | shower | TV

1 | 001 | 10 | 5

2 | 002 | 0 | 5

Answer

Try this:

SELECT ID, Car_num
   , SUM(IF(Service = 'shower', Price, 0)) AS Shower
   , SUM(IF(Service = 'TV', Price, 0)) AS TV
FROM your_table
GROUP BY Car_num;