2017-04-06 63 views
2

我有兩個表如下圖所示:SQL Server:如何從另一個表中選擇表中缺失的行?

表1

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

表2

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

我想選擇從表1列於表2人失蹤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 

下面是測試創建和插入查詢。

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 

謝謝

回答

4

你需要得到所有SKU和表的列表,然後只顯示其不會出現在表1行:

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) 
+0

太感謝你了。你是一個很好的幫助。 – Amir

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 
相關問題