Mark duplicate fields in a table

Asked

Viewed 416 times

3

I have a table in my database and I would like to mark the occurrences where a certain code is repeated. Remembering that this code field is not a primary key.

Example:

Data        Código    Repetição   Status    ...
25/2/2014   138863    ok          C96       ...
25/2/2014   387707    ok          C96       ...
25/2/2014   387707    nok         C96       ...
25/2/2014   387707    nok         C96       ...
25/2/2014   387707    nok         C96       ...
25/2/2014   1845141   ok          C96       ...
25/2/2014   1845141   nok         C96       ...
25/2/2014   1845141   nok         C96       ...
25/2/2014   1845141   nok         C96       ...
25/2/2014   1845141   nok         C96       ...
25/2/2014   1845141   nok         C96       ...

Does anyone have any idea how I can create the repeat column with the above logic (first occurrence, mark as ok, in the other nok) using some query?

At the moment I am using this table in a Access Database.

  • 1

    Use the GROUP BY clause and count the number of repetitions. The HAVING cont(*) > 1 clause can help you filter only repetitions.

  • You can ask the question the source tables?

1 answer

6


It is possible with a subquery that returns an element by code.

Let’s take an example with the structure below:

create table teste (
    id int primary key auto_increment,
    codigo int,
    repeticao  varchar(10)
);

The following query returns a ok only once per code:

select
  codigo,
  case
    when id = (
      select min(t2.id)
      from teste t2
      where t2.codigo = teste.codigo
    )
    then 'ok'
    else 'nok'
  end repeticao
from teste

See the sqlfiddle


In update form, you can do so:

UPDATE teste
SET repeticao = 
    case
        when id = (
            select min(t2.id)
            from (select * from teste) t2
            where t2.codigo = teste.codigo
        )
        then 'ok'
        else 'nok'
    end;

Note that Mysql does not allow selecting the table itself in a subselect in the command UPDATE, but the stretch (select * from teste) is a workaround to circumvent this limitation.

See the sqlfiddle

  • 1

    Great reply @utliz. I needed to make a change to work in Access because it does not support case. SELECT Dados_Exportar.codigo, IIf(id=(select min(d2.id) from Dados_Exportar d2 where d2.codigo = Dados_Exportar.codigo),'ok','nok') AS rep FROM Dados_Exportar;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.