Вы можете использовать оператор MERGE
, чтобы удалить все повторяющиеся строки, кроме самой старой:
SQL Fiddle
Настройка схемы Oracle 11g R2 :
CREATE TABLE balance ( account, timestamp, active ) AS
SELECT 832076635, DATE '2018-03-02', 1 FROM DUAL UNION ALL
SELECT 832076635, DATE '2017-12-29', 1 FROM DUAL UNION ALL
SELECT 832076635, DATE '2017-10-01', 0 FROM DUAL;
Запрос 1 :
MERGE INTO balance src
USING (
SELECT RID
FROM (
SELECT ROWID AS rid,
ROW_NUMBER() OVER ( PARTITION BY account ORDER BY timestamp ASC ) AS rn
FROM balance
WHERE active = 1
)
WHERE rn > 1
) dst
ON ( src.ROWID = dst.RID )
WHEN MATCHED THEN
UPDATE SET active = 1
DELETE WHERE 1 = 1
Запрос 2 :
SELECT * FROM BALANCE
Результаты
| ACCOUNT | TIMESTAMP | ACTIVE |
|-----------|----------------------|--------|
| 832076635 | 2017-12-29T00:00:00Z | 1 |
| 832076635 | 2017-10-01T00:00:00Z | 0 |
Или просто удалите самый новый активный дубликат:
MERGE INTO balance src
USING (
SELECT RID
FROM (
SELECT ROWID AS rid,
ROW_NUMBER() OVER ( PARTITION BY account ORDER BY timestamp DESC ) AS rn,
COUNT(*) OVER ( PARTITION BY account ) AS ct
FROM balance
WHERE active = 1
)
WHERE rn = 1 AND ct > 1
) dst
ON ( src.ROWID = dst.RID )
WHEN MATCHED THEN
UPDATE SET active = 1
DELETE WHERE 1 = 1