如何从sql表中获取数据在日期之间不存在的数据

时间:2014-10-11 07:19:26

标签: sql sql-server exists not-exists

如何从sql表中获取数据在日期之间不存在的数据

我正在使用三张桌子

  1. 客户大师
  2. 每日发送
  3. EmptyCylinderRecd
  4. 我想找到不在DailydispatchEmptyCylinderRecd表中的客户。我已尝试过此查询,但预期结果未显示:

    select * 
    from CustomerMaster 
    where 
       not EXISTS (select * 
                   from DailyDispatch  
                   where OrderDate between '1/22/2014' and '08/10/2014') or 
       not exists (select * 
                   from EmptyCylinderRecd 
                   where Date between '1/22/2014' and '08/10/2014')
    

3 个答案:

答案 0 :(得分:0)

Name is the common field

然后试试这个:

select * 
from CustomerMaster where Name NOT IN 
(select Name from DailyDispatch  
where CAST(OrderDate as DATE) between '2014-01-22' and '2014-08-10' 
and Name is NOT NULL )

union 

select * 
from CustomerMaster where Name NOT IN 
(select Name from EmptyCylinderRecd 
where  CAST(Date as DATE)between '2014-01-22' and '2014-08-10'
and Name is NOT NULL)

注意:如果您使用具有正确索引的CustomerID列之类的列会更好 在上面。 Union将提供query1和query2的常见结果。在性能方面使用Not Exists作为其他建议。 NOT IN vs NOT EXISTS

答案 1 :(得分:0)

SELECT * 
FROM   customermaster C 
WHERE  NOT EXISTS (SELECT 1 
                   FROM   dailydispatch D 
                   WHERE  C.NAME = D.NAME 
                         AND D.orderdate BETWEEN '2014-22-1' AND '2014-08-10') 
        OR NOT EXISTS (SELECT 1 
                       FROM   emptycylinderrecd E 
                       WHERE  C.NAME = E.NAME 
                              AND E.date BETWEEN '2014-22-1' AND '2014-08-10') 

答案 2 :(得分:0)

如果DailyDispatch或EmptyCylinderRecd中的[Name]列可以为null(列定义),我会投票给NOT IN解决方案,因为这可能会导致错误的结果。

相反,我会使用“NOT EXISTS”方法:

SELECT cm.* 
FROM CustomerMaster cm
WHERE 
NOT EXISTS 
    (SELECT 1 
     FROM DailyDispatch dp 
     WHERE cm.YourCol1 = dp.YourCol1 AND dp.OrderDate BETWEEN '20140122' and '20140810'
     )
OR NOT EXISTS
    (SELECT 1 
     FROM EmptyCylinderRecd ecr 
     WHERE cm.YourCol1 = ecr.YourCol1 AND ecr.[Date] BETWEEN '20140122' and '20140810'
    )

请注意,我将日期格式更改为符合ISO标准,以避免因DATEFORMAT设置而导致错误的结果或错误。