SQL Server:如何从另一个表中选择表中缺少的行?

时间:2017-04-06 11:40:49

标签: sql-server

我有两张如下表:

表1

StoreId SKU
------------
1       abc
2       abc
3       abc
1       xyz
4       xyz

表2

 StoreId
 --------
    1
    2
    3
    4
    5

我想从table1中的表1中选择缺少的storeid。但条件是在上面的示例中,SKU abc storeid 4和5缺失,而sku xyz 2,3,5缺失。所以我想在下表作为输出

SKU,ID
------
abc 4
abc 5
xyz 2
xyz 3
xyz 5

我只能使用以下查询来提取整体缺失的商店。

 SELECT 
     SKU, t2.StoreId 
 FROM 
     @table1 t1 
 FULL OUTER JOIN
     @table2 t2 ON t1.StoreId = t2.StoreId 
 WHERE
     t1.StoreId IS NULL

下面是test create和insert查询。

Declare @table1 As table
(
 StoreId varchar(4),
 SKU varchar(5)
)

Declare @table2 As table
(
 StoreId int
)
BEGIN
Insert Into @table1(SKU,StoreId) values('abc',1)
Insert Into @table1(SKU,StoreId) values('abc',2)
Insert Into @table1(SKU,StoreId) values('abc',3)
Insert Into @table1(SKU,StoreId) values('xyz',1)
Insert Into @table1(SKU,StoreId) values('xyz',4)
Insert Into @table2(StoreId) values(1)
Insert Into @table2(StoreId) values(2)
Insert Into @table2(StoreId) values(3)
Insert Into @table2(StoreId) values(4)
Insert Into @table2(StoreId) values(5)
END

谢谢

2 个答案:

答案 0 :(得分:4)

您需要获取所有skus和表的列表,然后仅显示未出现在table1中的行:

select SKU, StoreID
from @table2 t2
cross join (select distinct sku from @table1) t1
where not exists (select 1 from @table1 table1 
                  where table1.SKU = t1.SKU 
                    and table1.StoreId = t2.StoreId)

答案 1 :(得分:1)

这是一个具有相同结果的替代解决方案。

语法与@BeanFrog的答案非常相似:

SELECT
  t3.SKU, t2.StoreID
FROM
  @table2 t2
CROSS JOIN
  (SELECT distinct SKU
   FROM @table1) t3
LEFT JOIN
  @table1 t1 
ON
  t1.SKU = t3.SKU 
  and t1.StoreId = t2.StoreId
WHERE
  t1.sku is null
相关问题