2017-03-05 15 views
0

我想知道不在table2中的記錄。如何使用SQL Server檢索不在另一個表中的數據?

這裏我的查詢,

select 
    jj.ItemID, 
    jj.ItemLookupCode 
FROM 
    [JC_ItemDailySalesParent] jj 
left join [F_ItemDailySalesParent] ff 
on jj.ItemID != ff.ItemID 
    and year(ff.time)='2017' 
    and month(ff.time)='3' 
    and day(ff.time)='1' 
    and ff.StoreID='1400' 
where year(jj.time)='2017' 
    and month(jj.time)='3' 
    and day(jj.time)='1' 
    and jj.StoreID='1400' 

當我做計數的[JC_ItemDailySalesParent]是
和[F_ItemDailySalesParent]計數。

select 
    storeid, 
    count(Storeid) 
from [JC_ItemDailySalesParent] 
where year(time)='2017' and month(time)='3' and day(time)='1' 
group by StoreID 

select 
    storeid, 
    count(Storeid) 
from [F_ItemDailySalesParent] 
where year(time)='2017' and month(time)='3' and day(time)='1' 
group by StoreID 

計數結果

StoreID count 
1001  217 
1201  3140 
1302  5635 
1400  5422 
2001  5541 
2400  4565 

StoreID count 
1001  210 //want to know these missing 7 records from above table 
1201  3075 
1302  5607 
1400  5394 
2001  5469 
2400  4542 
+1

你應該真的使用日期標準,'ff.time> ='20170301和ff.time <'20170302'',而不是阻止索引被使用的函數 –

+0

@Jamesz給它一個。我想得到那個記錄。你能幫忙嗎? –

回答

0

你可以在這裏使用一個子查詢,而不是將兩個表:

SELECT 
    jj.ItemID, 
    jj.ItemLookupCode 
FROM 
    [JC_ItemDailySalesParent] jj 
WHERE 
    jj.ItemID NOT IN (
     SELECT ff.ItemID FROM [F_ItemDailySalesParent] ff 
     WHERE year(ff.time)='2017' 
      AND month(ff.time)='3' 
      AND day(ff.time)='1' 
      AND ff.StoreID='1400') 
    AND year(jj.time)='2017' 
    AND month(jj.time)='3' 
    AND day(jj.time)='1' 
    AND jj.StoreID='1400' 

而且你應該使用BETWEEN功能或比較操作@JamesZ說,而不是日期時間函數。

相關問題