Reputation: 325
I have a dates table and a customer fact table like below. I want to try to get the customer code on the dates left over that do not match the customer fact table. I'm not sure what to do in SQL to get this.
Dates:
Day of year| TY Date | LY Date
-----------+----------+---------
200 | 2/1/2015 | 2/2/2014
201 | 2/2/2015 | 2/3/2014
202 | 2/3/2015 | 2/4/2014
203 | 2/4/2015 | 2/5/2014
204 | 2/5/2015 | 2/6/2014
205 | 2/6/2015 | 2/7/2014
Cust:
Cust # | Day of Year | TY Date | LY Date
-------+-------------+----------+--------
300 | 203 | 2/4/2015 | 2/5/2014
900 | 205 | 2/6/2015 | 2/7/2014
RESULT:
Cust # | Day of Year | TY Date | LY Date
-------+-------------+----------+--------
300 | 200 | 2/1/2015 | 2/2/2014
300 | 201 | 2/2/2015 | 2/3/2014
300 | 202 | 2/3/2015 | 2/4/2014
300 | 204 | 2/5/2015 | 2/6/2014
300 | 205 | 2/6/2015 | 2/7/2014
900 | 200 | 2/1/2015 | 2/2/2014
900 | 201 | 2/2/2015 | 2/3/2014
900 | 202 | 2/3/2015 | 2/4/2014
900 | 203 | 2/4/2015 | 2/5/2014
900 | 204 | 2/5/2015 | 2/6/2014
Upvotes: 0
Views: 45
Reputation: 44891
One possible solution:
You can find the missing rows by first generating the complete set of possible pairs of Cust #
and Day of Year
, and then use that set as a derived table and do a left join with the Cust table and filter out the rows that are null, which will be the missing ones.
This query:
select a.*
from (
select [Cust#], d.[Day of year] from cust, dates as d
) a
left join Cust as c on c.[Cust#] = a.[Cust#] and c.[Day of Year] = a.[Day of year]
where c.[Cust#] is null
order by a.[Cust#], a.[Day of Year]
would give you the following result:
Cust# Day of year
300 200
300 201
300 202
300 204
300 205
900 200
900 201
900 202
900 203
900 204
Upvotes: 2