2017-03-05 63 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说,而不是日期时间函数。

相关问题