I don't know how to ask this correctly - it was probably asked many times. I have two tables. Companies and budgets.
Companies [id,name,address]
Budgets [id,company_id,year,budget]
I want to create a select where I would get the result for each company and budgets for each year in the same row.
budgets table:
id | company_id | year | budget
1 | 1 | 2018 | 1500
2 | 1 | 2019 | 2500
3 | 2 | 2018 | 700
4 | 2 | 2019 | 6000
So I would like to get the budgets in year columns
SELECT
a.id,
a.`name`,
IF(b.season_id = 1,b.budget,'') AS "budget 2018",
IF(b.season_id = 2,b.budget,'') AS "budget 2019"
FROM companies AS a
INNER JOIN budgets AS b ON a.id = b.company_id
This of course returns double rows. :)
company name | budget 2018 | budget 2019
company one | 1500 |
company one | | 2500
company two | 700 |
company two | | 6000
How can I get the budgets in the same row?
company name | budget 2018 | budget 2019
company one | 1500 | 2500
company two | 700 | 6000
Or how is this procedure called/described so I can ask uncle google? :)
Edit: I got suggestions for solving this task with outer joins. Truthfully I haven't had the time to solve the problem with outer joins - not yet confident if I can trust the result. The other thing is that I find the title of the suggested solution somewhat misleading. I ended solving this problem with the use of "fake" aggregates. Because this is a task I need once a year for a custom export I won't be pursuing a "better" solution. Thank you for your input.