如何使用SQL Server检索不在另一个表中的数据?

时间:2017-03-05 07:14:00

标签: sql sql-server stored-procedures

我想知道table2中没有的记录。

这是我的查询,

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]是 217 时 并且[F_ItemDailySalesParent]的计数 210

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 个答案:

答案 0 :(得分: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'

正如@JamesZ所说,你可能应该使用BETWEEN函数或比较操作而不是datetime函数。