Reputation: 3364
I run into road block and here is my issue:
I have a table, let's call it Items where all the items in my catalog are listed. I have ItemSold where it lists each item sold on which day. I have another table called Sales where it has the dates I want to enquiry about.
This is my illustration:
It is obviously trivial to find out what items sold on which day. My challenge is figuring out which items not sold on which day.
I have tried:
select i.itemid from items i
where i.ItemID not in ( SELECT i.ItemID
FROM Sales d INNER JOIN
ItemSold i ON d.SaleDate = i.SaleDate)
But that only provides me with the items not sold at all.
I am looking the following result:
I am using MSSQL. I have attached the script to recreate the tables and data:
CREATE TABLE [dbo].[Items](
[ItemID] [int] NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[ItemSold](
[SaleDate] [date] NULL,
[ItemID] [int] NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[Sales](
[SaleDate] [date] NULL
) ON [PRIMARY]
GO
I would appreciate your help. This is a simplified version of a pretty confusing issue at work.
Upvotes: 0
Views: 43
Reputation: 1270091
You first generate all the possible rows -- all dates and all items. Then use left join
to filter out the ones that have been sold:
select i.itemid, s.saledate
from items i cross join
sales s left join
itemsold si
on si.itemid = i.itemid and si.saledate = s.saledate
where si.itemid is null;
Upvotes: 1