I have the following query:
SELECT pa.codigo,
@rownum:=@rownum+1 AS nro
FROM presupuestosa pa , (SELECT @rownum:=0) r WHERE pa.obra=18
AND pa.empresa=1 ORDER BY codigo ASC
I want that for each repeated code field, I can save the value 1 in rownum and otherwise rownonum has a value of 0, in such a way that these values serve as undicators. In other words, an example like this should yield as a result:
|Codigo |nro |
|3 | 0 |
|5 | 1 |
|5 | 1 |
|7 | 0 |
|8 | 0 |
|9 | 0 |
|11 | 1 |
|11 | 1 |
|12 | 0 |
I have tried to use the case statement trying to compare the current row of code with the next one, but I don't know how to do it, if anyone has any ideas I would appreciate it
Since this is a duplicate check, a possible solution would be a query like this:
This query will group by and return the number of records in each group
codigo, obra, empresa
in the column .total
The columnids
obtained withGROUP_CONCAT
is a plus, in case you are interested in knowing, for example, what the id of each repeated value are, they will be separated by|
.This will allow you simpler and easier to analyze results.
proof of concept
VER DEMO EN REXTESTER
I did a test based on real data (I didn't put all the records you show, just a few for brevity) and I put a case where there are three duplicates, to show that the query can have an interesting scope: know once how many duplicates are there...
Result:
Using a subquey that counts the records grouped by work and code, then a left join to translate the totals to 0 or 1.
you have to repeat the work id so that it groups well, that can perhaps be improved
a fidel: http://www.sqlfiddle.com/#!9/ca674b4/1
explaineishon
In the subquery, the records are grouped by work and code and counted, and a column is added
hayDupes
that is always equal to1
.The magic is manifested between the fact
HAVING total>1
that it only returns duplicate records (2 or more) and the transformation ofhayDupes = NULL
a0
in the outer query.That is: in the outer query, the column is returned
nro
with the valuehayDupes
that is always equal to1
, or if the subquery columnhayDupes
does not exist (IFNULL
) returns0
.Due to
LEFT JOIN
the fact that the outer query only includes results from the subquery that meet the condition of having the sameCodigo
.Finally, it is filtered by work id.
There may be a more efficient way using group theory to filter the intersection, but I didn't get that much =P (self join is what is generally used in these cases)
I would like to provide you with this query, it allows you to know if the record is repeated more than once, on the other hand, the word
asc
is redundant since it is sorted by defaultasc
.Hope this can help you.