SQL Server 2017. Having been running simple-to-intermediate SQL queries for many years, I'm having trouble wrapping my head around this one, as it's querying for information that doesn't actually exist.
Given a table called Activity with ProductId (int), PurchaseDate (datetime)
and some rows that look like this:
1 2020-10-31
1 2020-11-01
1 2020-11-02
1 2020-11-03
2 2020-10-31
2 2020-11-01
2 2020-11-03
2 2020-11-04
3 2020-10-31
3 2020-11-01
4 2020-10-31
4 2020-11-01
4 2020-11-03
5 2020-10-20
6 2020-10-31
6 2020-11-01
6 2020-11-02
And then another table called ProductIds with column ProductId (int) and 7 rows, with values 1-7:
I need to return from the Activity table any ProductIds that do not have an entry for a date from a date range, as well as the date that doesn't have the entry. This would be the results:
2 2020-11-02
3 2020-11-02
3 2020-11-03
4 2020-11-02
5 2020-10-31
5 2020-11-01
5 2020-11-02
5 2020-11-03
6 2020-11-03
7 2020-10-31
7 2020-11-01
7 2020-11-02
7 2020-11-03
So the query would be looking for any ProductId from the ProductIds table that does not have an associated entry in the Activity table for dates between 2020-10-31 and 2020-11-03.
This is what I have so far, but bangin' my head trying to figure it out:
SELECT ProductId, PurchaseDate
FROM dbo.Activity
WHERE ProductId NOT IN (SELECT ProductId FROM dbo.ProductIds);
I know there are at least a couple things wrong with that query and I just can't figure out how to go about this. As you can see, the results set is returning information that doesn't exist in the table, hence my confusion.
