-1

I have a table like this:

t1    t2    t3
1     01    M6
1     02    M6
2     01    M1
2     01    M1
2     02    M1
3     04    M4
3     04    M4
4     01    M1
4     01    M2

And I need to end up with something like this:

t1    t2    t3
1     01    M6
1     02    M6
2     01    M1
2     02    M1
3     04    M4
4     01    M1
4     01    M2

In other words, I need to:
for each t1, delete the rows that repeat themselves (leaving one of them) on t2 and at the same time have the same t3 value. If they repeat on t2 but have different t3, they won't be deleted.

Was testing with something like this but it's not quite there:

WITH cte AS (
    SELECT t1,
        RNum = ROW_NUMBER() OVER (PARTITION BY t2, t1 order by t3)
    FROM tbl
    )
DELETE FROM cte WHERE RNum > 1;
ovufo
  • 1
  • 1

3 Answers3

0

Execute a query like this:

DELETE from tbl WHERE ROWID in (
  SELECT DISTINCT dup.ROWID
  FROM tbl inner join tbl as dup ON tbl.t1 = dup.t1 AND tbl.t2 = dup.t2 AND tbl.t3 = dup.t3 AND dup.ROWID > tbl.ROWID
)
Bernhard
  • 4,855
  • 5
  • 39
  • 70
Marlin Pierce
  • 9,931
  • 4
  • 30
  • 52
0

With a CTE:

with cte as (
  select 
    t1, t2, t3, 
    ROW_NUMBER() OVER (PARTITION BY t1, t2, t3 order by t1, t2, t3) rn from tbl
)
delete from cte
where rn > 1;

See the demo

forpas
  • 160,666
  • 10
  • 38
  • 76
-1

Please try below. Hopefully it will help.

 delete from a
 from
 (select t1, t2, t3
       ,ROW_NUMBER() over (partition by t1, t2, t3
                      order by t1, t2, t3) RowNumber 
  from tbl) a
  where a.RowNumber > 1
Gaurav
  • 623
  • 5
  • 11