Skip to content
Advertisement

JOINING the Same Tables in SQL

I have a table with 4 columns such as Customer ID, Person ID, Year, Unit Cost.

enter image description here

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:

enter image description here

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;        
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement