I have a table with 4 columns such as Customer ID, Person ID, Year, Unit Cost.
I want to join the same table with all the years from table and keep the all years for all customer ID and PErson ID’s. IF there is no data in the table for respective customer ID and PErson ID then I want the Cost as NULL. Expected Data:
Advertisement
Answer
If I understand correctly, you can use a cross join
to generate the rows and a left join
to bring in the existing data:
select pc.*, y.*, t.cost from (select distinct customer, personid from customer_table) pc cross join (select distinct year from customer_table) y left join customer_table t on t.customer = pc.customer and t.personid = pc.personid and t.year = y.year;