Skip to content
Advertisement

SQL join condition either A or B but not both A and B

I have sales data by years and quarters and for the last year I want to fill missing quarters with last available value.

Say we have source table:

Desired results:

So the task is to make Cartesian of year and quarter and left join to it the sales either corresponding or the last.

This code gets me almost there:

How to correct the last line (condition of join) so thet the 2018 is not doubled?

Advertisement

Answer

One method uses outer apply:

For your volume of data, this should be fine.

A more efficient method — assuming you are only assigning values to the end — would be:

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement