db2 删除行,以便一个名字只存在一行

jaxagkaj  于 2022-12-04  发布在  DB2
关注(0)|答案(2)|浏览(151)

我创建了表。

CREATE TABLE test_tab(
ID INT,
FIRSTNAME VARCHAR(40),
TS TIMESTAMP)

并在其中插入值。

INSERT INTO test_tab (ID, FIRSTNAME, TS) VALUES (1, 'Jhon', '2018-06-05 00:11:56');
INSERT INTO test_tab (ID, FIRSTNAME, TS) VALUES (2, 'Jhon', '2018-06-15 00:14:56');
INSERT INTO test_tab (ID, FIRSTNAME, TS) VALUES (3, 'Jhon', '2018-06-19 00:10:56');
INSERT INTO test_tab (ID, FIRSTNAME, TS) VALUES (4, 'Mike', '2018-06-05 00:10:56');
INSERT INTO test_tab (ID, FIRSTNAME, TS) VALUES (5, 'Mike', '2018-06-15 00:10:56');
INSERT INTO test_tab (ID, FIRSTNAME, TS) VALUES (6, 'Mike', '2018-06-20 00:10:56');
INSERT INTO test_tab (ID, FIRSTNAME, TS) VALUES (7, 'Lis', '2018-06-05 00:13:56');
INSERT INTO test_tab (ID, FIRSTNAME, TS) VALUES (8, 'Lis', '2018-06-15 00:17:56');
INSERT INTO test_tab (ID, FIRSTNAME, TS) VALUES (9, 'Lis', '2018-06-21 00:10:56');

我需要删除行,这样只有一个名字存在一行,留下最大TS的行。这是我的请求的例子。我如何删除它?

SELECT DISTINCT firstname
FROM test_tab
GROUP BY firstname
HAVING COUNT(firstname) > 1
union 
select firstname from test_tab where ts = (select max(ts) from test_tab)
r9f1avp5

r9f1avp51#

试试这个

DELETE FROM TEST_TAB T
WHERE NOT EXISTS
(
  SELECT 1
  FROM TEST_TAB G
  WHERE G.FIRSTNAME = T.FIRSTNAME
  HAVING MAX (G.TS) = T.TS
);

SELECT * FROM TEST_TAB;

| 识别码|姓名|技术支持|
| - -|- -|- -|
| 三个|琼|2018年6月19日00:10:56.000000|
| 六个|麦克|2018年6月20日00:10:5600万|
| 九个|利斯|2018年6月21日00:10:56.000000|
fiddle

m4pnthwp

m4pnthwp2#

只要与基础表存在双射,就可以从派生表中删除:

delete from (
    select t.*, row_number() over (partition by FIRSTNAME order by ts) as rn
    from test_tab t
)
where rn > 1;

Fiddle

相关问题