1
I have a table Serviços(Nro_Serv, Data, Cliente, Valor)
and would like to get customers who did service with me in a year X (ex: 2011) and who also did in a year Y (ex: 2012). I tried to use COUNT(*)
and then GROUP BY Cliente HAVING COUNT(*) > 1
. But you’re not giving a real value.
Code of SQL
:
SELECT cliente.nmcliente, COUNT(*)
FROM ordemservico
INNER JOIN cliente
ON ordemservico.cdcliente = cliente.cdcliente
WHERE ordemservico.auxordemservico = '/12'
OR ordemservico.auxordemservico = '/13'
GROUP BY cliente.nmcliente
HAVING COUNT(*) > 1
The auxordemservico field is a field with year suffix.
Editing
I changed the SQL
and I did the following:
SELECT cliente.nmcliente, ordemservico.auxordemservico, COUNT(*)
FROM ordemservico
INNER JOIN cliente
ON ordemservico.cdcliente = cliente.cdcliente
WHERE ordemservico.auxordemservico = '/12'
OR ordemservico.auxordemservico = '/13'
GROUP BY cliente.nmcliente, ordemservico.auxordemservico
HAVING COUNT(*) > 1
Now he returns to me clearly all customers who did services in the two years. I need to take out the ones that are not duplicated first, because I care who did services in the two years. And after that apply a "Distinct".
Could add to the question the SQL you wrote?
– Tony
If the field ordemservico.auxordemservico has the year prefixed should not start with the year (2011 or 2012 as you put it in the explanation)? Post the definition of your tables to facilitate those who want to help you.
– user4552
@Osvaldo, was more for example. I want to compare two different years.
– Matt S
@Strokes: I don’t understand your explanation of the ordemservico.auxordemservico field, you say that the year is a prefix but you put it after the bar (so it would be a suffix). Is this all the content of the field or just part of it? The use of the data field, as proposed by Silvio Andorinha, does not meet your needs?
– user4552
@Osvaldo, it represents a year and is a suffix (misspelled). Yes, this "/12" and "/13" is what it stores.
– Matt S
@Strokes: When you say you’re not giving a real value is because you might be considering customers who have done more than one service in a single year? If it is that try to make a Join with those who did service in a year "and" also with those who did the next year.
– user4552
@Osvaldo, I believe it returns both customers who did services in the years 2012 and 2013, as well as those who only did in 2012 OR 2013.
– Matt S