尝试将重复行合并在一起,错误最多指定多次

时间:2017-06-30 23:43:33

标签: sql postgresql

我有一个包含大量条目的数据库,其中一些条目可能如下所示:

| id | name | field1 | field2 | field3 |
----------------------------------------
| 1  | id1  | 2      | 3      |        |
| 2  | id2  | 2      | 1      |        |
| 3  | id1  |        |        | 5      |
| 4  | id2  |        |        | 8      |

我正在尝试运行以下SQL语句将类似的行合并在一起,然后将它们放回到表中:

SELECT name, max(id), max(field1), max(field2), max(field3) INTO groups FROM groups GROUP BY name;

我希望能给我:

| id | name | field1 | field2 | field3 |
----------------------------------------
| 3  | id1  | 2      | 3      | 5      |
| 4  | id2  | 2      | 1      | 8      |

但是这句话只给了我ERROR: column "max" specified more than once

我的陈述有什么问题?谢谢你的帮助!

2 个答案:

答案 0 :(得分:2)

您使用的语法不正确,因为select ... into ...会创建一个新表。您想要更新或删除现有表中的行。您可以使用公用表表达式来执行此操作:

with new_rows as (
    select 
        name, 
        max(id) as id, 
        max(field1) as field1, 
        max(field2) as field2, 
        max(field3) as field3
    from groups 
    group by name
),
deleted_rows as (
    delete from groups
    where id not in (
        select id 
        from new_rows
        )
    )
update groups g
set field1 = n.field1, field2 = n.field2, field3 = n.field3
from new_rows n
where n.id = g.id
returning g.*;

 id | name | field1 | field2 | field3 
----+------+--------+--------+--------
  3 | id1  |      2 |      3 |      5
  4 | id2  |      2 |      1 |      8
(2 rows)    

答案 1 :(得分:1)

您只需从查询中取出INTO xxx,并为列添加别名,以便以后区分它们:

-- Aliasing columns
SELECT 
    name, max(id) AS id, max(field1) AS field1, max(field2) AS field2, max(field3) AS field3
FROM 
    groups 
GROUP BY 
    name;

......你得到了

name | id | field1 | field2 | field3
:--- | -: | -----: | -----: | -----:
id1  |  3 |      2 |      3 |      5
id2  |  4 |      2 |      1 |      8

检查dbfiddle here

的所有内容

正如 klin 在他/她的回答中所提到的,SELECT INTO创建了一个新表,并且在没有列别名的情况下,会将多个列称为max。见PostgreSQL SELECT INTO