1
Something very unusual happened in my bank. Some records were entered more than once (7 to 13) to be exact. This occurred due to software error that has already been solved.
Now I need to delete duplicate records, but I have the following scenario:
- The records that were not moved, I can leave only the smallest Id;
- The records that all copies were moved together I leave only the smallest Id;
- but by some trick of fate, I have the third case. Some duplicates moved alone, that is, of the 7 copies only one was correct and the others did not follow.
Getting to the heart of the matter, is it possible to make an "if" within a select? I made this query that returns to me the following:
SELECT IdLoteProduto ,
Serie ,
Saiu ,
COUNT(Id) AS cont ,
MIN(Id) AS old
FROM dbo.SerieProduto
WHERE empresa = 385
AND IdLoteProduto = 264
GROUP BY IdLoteProduto ,
Serie ,
Saiu
This query returns me the following information:
Id Serie Saiu Rep Id mais antigo
264 8955031700194659020 0 6 2217691
264 8955031700194659020 1 1 2217721
This in a query that returns all the values.
I wonder if there is way in this case select the Id of the second option, however, in the cases below it return me the correct numbers.
Id Serie Saiu Rep Id mais antigo
264 8955031700194659020 0 7 1234567
264 8955031700194659021 1 7 1234897
In this case they are different serials I mean, I must return the Id of the first and the second.
I hope I was clear.
Please, if you can improve my question, tell me how, what I will do.
I’m not sure I understand: you need to make a
MIN(id)
when in a case, andMAX(id)
when in another? What is the criterion for knowing when to do theMAX(id)
? At first I would suggest usingCASE
, but depending on the complexity of the criterion it may be necessary to use "window function", asOVER()
...– nunks
Recurring problem, a Google search guarantee will bring almost ready solutions "remove duplicated records sql server"
– Motta
How do you know which record is correct?
– Sorack
@Motta I think you don’t understand, the duplicate records are not the problem, the problem is that some duplicate records were not moved together, only one was and its copies were not, so this one was should be kept and its copies deleted
– Márcio Eric
@Sorack It is a rule somewhat simple, let’s say that I have a record with 7 identical copies, what should remain is the oldest, ie the smallest Id, but if this record is different from your copies, the different should be maintained.
– Márcio Eric
@nunks.lol Almost this, it would not be a MAX but the Id of the record that is different.
– Márcio Eric