我有以下查询,我需要它来返回这两个日期之间的所有空值。
select cust_first_name
from customers
join orders using(customer_id)
where order_date between (to_date('01-01-2007','DD-MM-YYYY'))
and (to_date('31-12-2008','DD-MM-YYYY'));
答案 0 :(得分:2)
听起来你想要的是在给定日期范围内没有订单的客户。您正在使用的联接发现与此相反。
您可以使用外部联接执行此操作,在这种情况下,您需要在联接之前应用日期过滤器。使用NOT IN或NOT EXISTS子查询可能更容易,更易读:
select cust_first_name
from customers
WHERE customers.customer_id NOT IN (
SELECT orders.customer_id from orders
where order_date between (to_date('01-01-2007','DD-MM-YYYY'))
and (to_date('31-12-2008','DD-MM-YYYY'))
)
答案 1 :(得分:-1)
以下是如何做你想做的事情的例子。
关键部分是在订单表上进行左连接,然后简单地在date1和date2之间执行
declare @customers table (
id int identity(1,1),
first_name nvarchar(50),
last_name nvarchar(50)
)
declare @orders table (
id int identity(1,1),
customer_id int,
order_date datetime
)
insert into @customers(first_name, last_name) values ('bob', 'gates')
insert into @customers(first_name, last_name) values ('cyril', 'smith')
insert into @customers(first_name, last_name) values ('harry', 'potter')
insert into @orders(customer_id, order_date) values (1, '2007-02-01')
insert into @orders(customer_id, order_date) values (2, '2015-02-15')
insert into @orders(customer_id, order_date) values (3, '2008-02-15')
select
customers.id
,customers.first_name
,customers.last_name
from @customers customers
left join @orders orders on orders.customer_id = customers.id
where orders.id is null
or orders.order_date not between ('2007-01-01') and ('2008-12-31')
group by
customers.id
,customers.first_name
,customers.last_name;