0

i have a database that contains a line for every action i made for a costumer for example:

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

i want to search which costumers didn't requested a repair in the latest year compared to the costumers i worked for the 2 years before

so i made a query as following

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');

still my query is returning lines for costumers i worked for latest year

what can be wrong with the query or is there a problem with my database data? what can be the cause??

4

2 回答 2

1

你正在做:

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

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

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');
于 2013-12-02T21:06:28.290 回答
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 年前的行数(根据您的定义)。你至少想要其中之一。

第二个子句计算最近一年的数字。这些你都不想要。这两个子句的组合就是您要寻找的客户。

于 2013-12-02T21:39:38.030 回答