仅当满足两个条件时才从 SQL 查询中排除结果

时间:2021-04-22 10:42:15

标签: sql sql-server-2008-r2

我有两个表,一个存储日期范围从今天(2021-04-22)到今天+5,第二个存储交货和产品。如果delivery_id 等于今天,我需要返回dates 表范围内的所有"CUSTOM",不包括deliveries.end_date 产品 (因此应包括 A01,但应排除 A02)。目前它排除了所有 "CUSTOM"

输出应包括以下列:

datess | delivery_id | product

表格:

  CREATE TABLE dates 
(
  datess DATETIME
);
INSERT INTO dates(datess)
VALUES
('2021-04-22 00:00:00.000'),
('2021-04-23 00:00:00.000'),
('2021-04-24 00:00:00.000'),
('2021-04-25 00:00:00.000'),
('2021-04-26 00:00:00.000'),
('2021-04-27 00:00:00.000')


CREATE TABLE deliveries 
(
  delivery_id VARCHAR(20),
  product VARCHAR(10),
  start_date DATETIME,
  end_date DATETIME,
);
INSERT INTO deliveries(delivery_id, product, start_date, end_date)
VALUES
('A01', 'CUSTOM', '2021-04-22', '2021-04-23'),
('A02', 'CUSTOM', '2021-04-21', '2021-04-22'),
('A03', 'NORMAL', '2021-04-01', '2021-04-30'),
('A04', 'NORMAL', '2021-04-22', '2021-04-24'),
('A05', 'NORMAL', '2021-04-19', '2021-04-22'),
('A06', 'NORMAL', '2021-04-20', '2021-04-20')

这是我的选择:

    declare @TodaysDate    datetime = CONVERT(DATETIME, CONVERT(DATE, CURRENT_TIMESTAMP)) + '00:00:00.000'
    declare @EndDate      datetime = dateadd(day,5,@TodaysDate)
    declare @TomorrowsDate      datetime = dateadd(day,1,@TodaysDate)
    
    select dt.datess, de.delivery_id, de.product from dates dt left join deliveries de
    on dt.datess between de.start_date and de.end_date
    and (de.end_date <> @TodaysDate AND de.product NOT LIKE '%CUSTOM%')
    
    order by delivery_id

1 个答案:

答案 0 :(得分:0)

<块引用>

只有在 delivery.end_date 等于今天时,我才需要返回日期表范围内的所有 delivery_id,不包括“CUSTOM”产品(因此应包括 A01,但应排除 A02)。

我不确定条件的第一部分是什么意思。但是你可以使用这个逻辑处理剩下的事情:

select d.*
from deliveries d
where not (d.product = 'CUSTOM' and d.end_date = (select min(da.datess) from dates da));

如果我理解第一个,你可以使用:

select d.*
from deliveries d
where not (d.product = 'CUSTOM' and d.end_date = (select min(da.datess) from dates da)) or
      (d.product <> 'CUSTOM' and
       d.start_date in (select da.datess from dates da) and
       d.end_date in (select da.datess from dates da)
      );

Here 是一个 db<>fiddle。