【问题标题】:How to get the data from sql table where data is not present in the between dates如何从日期之间不存在数据的sql表中获取数据
【发布时间】:2014-12-06 08:59:02
【问题描述】:

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

我正在使用三个表

  1. 客户大师
  2. 每日调度
  3. EmptyCylinderRecd

我想查找不在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')

【问题讨论】:

  • 能展示一下表格结构吗?
  • 表之间的关系是什么???
  • 三个表之间的关系是Name是公共字段
  • @Sarvan - 您希望客户出现在表 1 中,而不是 2,3 中?
  • @BoratSagdiyev 完全正确,我希望客户在表 1 中,而谁不在表 2,3 中。

标签: sql sql-server exists not-exists


【解决方案1】:

如果 DailyDispatch 或 EmptyCylinderRecd 中的 [Name] 列可以为空(列定义),我会投票反对 NOT IN 解决方案,因为这可能会导致不正确的结果。

相反,我会使用“不存在”的方法:

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 的设置而导致错误的结果或错误。

【讨论】:

    【解决方案2】:
    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') 
    

    【讨论】:

      【解决方案3】:
      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 ExistsNOT IN vs NOT EXISTS

      【讨论】:

      • 也许您的意思是“NOT IN”而不是“NOT”?
      • 通过 [OrderDate] 和 [Date] 的转换,参数不再是 SARGable,导致表扫描,即使存在支持索引。此外,如果内部选择中的列可以具有 NULL 值,则 NOT IN 可能会返回不正确的结果。因此,我强烈反对该解决方案。
      • @Ganesh_Devlekar-感谢您的回答,但我想在两个表中检查哪些数据不存在,我想显示不在 dailydispatch 和 EmptyCylreturn 表中的常用名称。这个查询是显示联合。
      猜你喜欢
      • 2023-01-26
      • 2021-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-01
      • 2011-11-25
      • 2013-10-19
      • 1970-01-01
      相关资源
      最近更新 更多