I have a table "messages"
['id', 'en', 'type', 'company_id']
i have two types
['new_contract', 'new_offer']
i may have two records with the same ‘type’ = ‘type’ but one with a company_id and one with a null ‘company_id’
i want to select all records with company_id =1 but if one type is missing for this company get the missing type record even if it’s null company_id
record 1 ['1', 'new contract', 'new_contract','1']
record 2 ['2', 'new offer', 'new_offer','2']
record 3 ['3', 'new offer', 'new_offer',NULL]
record 4 ['4', 'new contract', 'new_contract',NULL]
Output
record 1 ['1', 'new contract', 'new_contract', '1']
record 3 ['3', 'new offer', 'new_offer', NULL]
Not sure if that’s possible using sql your text
3
Answers
This reads like a prioritization question, where, for each type, you prefer the row of company 1 over the row where company is null.
One option uses window functions:
In the window function,
order by company_id desc
putsnull
values last – so this prioritizes the "other" type row, if any.To get all records of the company_id (if we have multiple rows of the same type) + the null records if there is a missing type, we can do something like this:
Just to show another option beside @GMB use of windowing functions — you take all the items with null and all those without and union them to get a list you want (union will remove duplicates) like