查找一条记录存在但另一条记录不存在的数据

Find data that exists for one record but not another record

我有两张桌子。 #tempinfo 包含订单号和客户名称。 #tempproduct 包含订单号、客户名称和订购的产品。

我需要查找存在于某个客户的一个订单中,但在该客户的另一个订单中缺失的产品。

create table #tempinfo (OrderNumber int, Client varchar(25))
create table #tempproduct (productid int, OrderNumber int, Client varchar(25), Products varchar(50)

insert into #tempinfo values (1, 'Albertsons')
insert into #tempinfo values (2, 'Albertsons')
Insert into #tempinfo values (3, 'Krogers')
Insert into #tempinfo values (4, 'Krogers')
Insert into #tempinfo values (5, 'Krogers')
Insert into #tempinfo values (6, 'Smiths')
Insert into #tempinfo values (7, 'Smiths')

insert into #tempproduct (1, 1, 'Albertsons', 'Oranges')
insert into #tempproduct (2, 1, 'Albertsons', 'Apples')
insert into #tempproduct (3, 2, 'Albertsons', 'Oranges')
insert into #tempproduct (4, 2, 'Albertsons', 'Apples')
insert into #tempproduct (5, 2, 'Albertsons', 'Grapes')
insert into #tempproduct (6, 3, 'Krogers', 'Pencils')
insert into #tempproduct (7, 3, 'Krogers', 'Pens')
insert into #tempproduct (8, 3, 'Krogers', 'Staples')
insert into #tempproduct (9, 5, 'Krogers', 'Pencils')
insert into #tempproduct (10, 5, 'Krogers', 'Erasers')
insert into #tempproduct (11, 6, 'Smiths', 'Soda')
insert into #tempproduct (12, 6, 'Smiths', 'Buns')
insert into #tempproduct (13, 6, 'Smiths', 'Ice')
insert into #tempproduct (14, 7, 'Smiths', 'Buns')

我想看看: Albertsons 订单 1 丢失 'Grapes' Krogers 订单 3 丢失 'Erasers' Krogers 订单 5 丢失 'Pens' 和 'Staples' 史密斯订单 7 缺失 'Soda' 和 'Ice'

这是一个有趣的问题。这个想法是为客户生成所有行——也就是说,为客户的每个订单生成所有产品。

然后使用 left join 找到匹配的,并过滤掉这些:

select cp.client, cp.product, co.ordernumber
from (select distinct client, product from tempproduct) cp  join
     (select distinct client, ordernumber from tempproduct) co
     on cp.client = co.client left join
     tempproduct tp
     on tp.client = cp.client and
        tp.product = cp.product and
        tp.ordernumber = co.ordernumber
where tp.client is null;

Here 是一个 db<>fiddle.