Pregunta

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??

¿Fue útil?

Solución

You are doing:

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

Most likely customername is not a datefield :p. You should change date to 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');

Otros consejos

You can actually approach this problem with a having clause:

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;

What this is doing is looking at all the records for a given customer (because of the group by clause). The first clause in the having statement counts the number of rows where the date is 2 years ago (by your definition). You want at least one of these.

The second clause counts the number that are in the more recent year. You want none of these. The combination of these two clauses are the customers you are looking for.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top