查询搜索不返回的行

时间:2013-12-02 21:00:46

标签: sql notin

我有一个数据库,其中包含我为客户制作的每个操作的行 例如:

12/11/13;costumer name a; actions performed
13/11/13;costumer name b; another action performed
..................................

我想搜索哪些客户在最近一年没有要求维修,而不是我之前工作的客户

所以我按照以下方式进行了查询

select distinct costumername
from BEZOE
where date BETWEEN '2009-06-30 00:00:00.000'
AND '2011-06-30 00:00:00.000'
and date not in(
    select costumername from BEZOE where date between '2011-06-30 00:00:00.000'
AND '2012-06-30 00:00:00.000');

我的查询仍然是为我去年工作的客户返回的行

查询可能出错 或者我的数据库数据有问题吗? 可能是什么原因??

2 个答案:

答案 0 :(得分:1)

你在做:

... date not in( select costumername ...

最有可能的客户名称不是日期字段:p。您应该将date更改为costumername

select distinct costumername
from BEZOE
where date BETWEEN '2009-06-30 00:00:00.000'
AND '2011-06-30 00:00:00.000'
and costumername not in(
    select costumername from BEZOE where date between '2011-06-30 00:00:00.000'
AND '2012-06-30 00:00:00.000');

答案 1 :(得分:0)

您实际上可以使用having子句来解决此问题:

select costumername
from BEZOE
group by costumername
having sum(case when date between '2009-06-30 00:00:00.000' and '2011-06-30 00:00:00.000'
                then 1 else 0
           end) > 0 and
       sum(case when date between '2011-06-30 00:00:00.000' and '2012-06-30 00:00:00.000'
                then 1 else 0
           end) = 0;

这样做是为了查看给定客户的所有记录(因为group by子句)。 having语句中的第一个子句计算日期为2年前的行数(根据您的定义)。你至少想要其中一个。

第二个条款计算最近一年的数字。你不想要这些。这两个条款的组合是您正在寻找的客户。