【问题标题】:Get data using the Date Range when 'WHERE NOT EXISTS' is used使用“WHERE NOT EXISTS”时使用日期范围获取数据
【发布时间】:2021-03-19 03:22:31
【问题描述】:

在 SQL Server 中使用 'WHERE NOT EXISTS' 时,我需要使用以下查询中提到的日期范围从表中获取数据。

declare @Start DATETIME, 
        @End DATETIME 

    Set @Start = '01/01/2020'
    Set @End  = '01/15/2020'

select A.request_id, A.order_id
       from table_a A
where not exists (select * from table_b B where B.request_id=A.request_id 
       and B.order_id=A.order_id)
and WHERE (provided_date between @Start and @End)

需要包含WHERE provided_date between @Start and @End

应用日期范围时,我需要提供的日期范围的数据。我如何实现这一目标? 请找到下表和预期输出:

**TABLE A**

request_id|order_id|Provided_Date
10        |2567    |01/01/2020
20        |4784    |01/03/2020
30        |2578    |01/07/2020
40        |8432    |01/10/2020
50        |9032    |01/13/2020

**TABLE B**

request_id|order_id|Provided_Date
30        |2578    |01/07/2020
40        |8432    |01/10/2020

**EXPECTED OUTPUT**

request_id|order_id|Provided_Date
10        |2567    |01/01/2020
20        |4784    |01/03/2020
50        |9032    |01/13/2020

【问题讨论】:

  • 请提供样本数据和期望的结果。还要解释为什么您使用不受支持的 SQL Server 版本。
  • 您为什么要标记 2 个在几年前就已报废的 SQL Server 版本?你真的在使用那些版本吗?如果是这样,您确实应该优先使用更新的版本。
  • 至于问题,你尝试了什么?为什么不能在您拥有的WHEREs 的适当位置包含您显示的子句?
  • @Larnu 我使用的是 2012 MSSQL 版本,现在包含该子句,就像我之前使用的方式一样,并添加了如何需要输出的示例
  • and WHERE (provided_date between @Start and @End) 中删除WHERE。它应该只是阅读and (provided_date between @Start and @End)。而SELECT * 中的NOT EXISTS 应该是SELECT 1,因为您不需要返回测试中的任何列,而且您绝对不需要返回所有列 - 您只需要知道该行是否存在。

标签: sql sql-server tsql sql-server-2012


【解决方案1】:

当您发布问题时,请与我们分享您的表结构(CREATE TABLE ...)和一些示例数据(INSERT INTO ...) 以及您的预期结果。这样我们才能找到正确的方向并进行一些测试。

试试:

declare @Start DATETIME, 
        @End DATETIME 

Set @Start = '01/01/2020'
Set @End  = '01/15/2020'

select request_id, order_id,Provided_Date
from table_a 
where request_id not in (select request_idfrom table_b )
      and provided_date between @Start and @End

【讨论】:

    猜你喜欢
    • 2019-02-10
    • 1970-01-01
    • 1970-01-01
    • 2018-01-08
    • 2016-10-06
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多