0

I would like to create a column that increments each time the same value is found in the first column. These fields could be strings, or integers. Something like:

field1 | field2
cat | 1
fish | 1
dog | 1
cat | 2
fish | 2
cow | 1

My question is similar to these two (1), (2), but I do not want to INSERT or UPDATE if the key already exists. I want to delete the second record. So, something like DELETE FROM t1 WHERE field2 > 1.

This question (MySQL delete duplicate records but keep latest) is MOST similar to what I'm trying to do, except instead of having an integer auto-incremented ID column, I have another field called filename, which would be different for each repeated field1.

Is this called an aggregate function? How to accomplish this?

raw-bin hood
  • 5,839
  • 6
  • 31
  • 45

1 Answers1

0

What you seem to be asking for is counting a particular value. So, if you are trying to count 1 values and you have an ordering column, then:

select t.*, sum(field1 = 1) over (order by <ordering column>) as field2
from t;

However, your results suggests that you just want an enumeration of each independent value. That would be:

select t.*, row_number() over (partition by field1 order by <ordering column>) as field2
from t;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • I can't use row_number() since I'm on MariaDB 5.5. – raw-bin hood Sep 11 '20 at 18:40
  • I'm not trying to simply get the count of times that value is present such as `SELECT field1, count(*) as field2 FROM t1 GROUP BY field1 HAVING field2 > 1 ORDER BY field2 DESC`. I can edit the example above to include a better. – raw-bin hood Sep 11 '20 at 18:47
  • I Googled the term `ordering column SQL` and found no references to this structure. Do you have a link to explain what that is? – raw-bin hood Sep 11 '20 at 18:50