Home > Software design >  MySQL Select single column into multiple column
MySQL Select single column into multiple column

Time:02-24

So, I have the following table (gross example):

CREATE TABLE budget_details(
    detail_id INT PRIMARY KEY,
    budget_id INT FOREIGN KEY,
    detail_month VARCHAR(16),
    total DECIMAL(18,2)
)

I'm trying to Select a Single Row with budget_id and have different columns for each Month (eg. January, February, etc) displaying their total, and all the other months null, showing 0, idc, something like this Example of results

I know it'd be easier to just recreate the table, but it's an old software and i'd break a lot of stuff

Any and all help is appreciated

CodePudding user response:

The query below provides the result as shown in your image.

 SELECT 
   detail_id,
   budget_id, 
  CASE WHEN detail_month = 'January' THEN total END AS 'January',
  CASE WHEN detail_month = 'February' THEN total END AS 'February',
  CASE WHEN detail_month = 'March' THEN total END AS 'March'
FROM 
 budget_details
ORDER BY
   detail_id,
   budget_id
  • Related