在 PostgreSQL 8.3 中,假设我有一个名为 widgets
的表,其中包含以下内容:
id | type | count
--------------------
1 | A | 21
2 | A | 29
3 | C | 4
4 | B | 1
5 | C | 4
6 | C | 3
7 | B | 14
我想根据 type
列删除重复项,只留下表中 count
列值最高的那些。最终数据如下所示:
id | type | count
--------------------
2 | A | 29
3 | C | 4 /* `id` for this record might be '5' depending on your query */
7 | B | 14
我觉得我很接近,但我似乎无法全神贯注于一个可以消除重复列的查询。
最佳答案
count
是一个 sql 保留字,因此必须以某种方式对其进行转义。我记不起在 Postgres 中执行此操作的语法,所以我只是用方括号将其括起来(如果不正确,请更改它)。无论如何,以下内容理论上应该有效(但我没有实际测试):
delete from widgets where id not in (
select max(w2.id) from widgets as w2 inner join
(select max(w1.[count]) as [count], type from widgets as w1 group by w1.type) as sq
on sq.[count]=w2.[count] and sq.type=w2.type group by w2.[count]
);
关于sql - 删除SQL中的相似列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1659575/