postgres将groupby的最小记录移动到另一个表

时间:2017-03-27 21:23:29

标签: postgresql

我在postgres中有一个名为t1的表。我需要在字段a,b和c上对t1进行分组。然后,我需要选择groupby中的所有记录,以外的字段d中具有最小值的记录,并将它们移动到表t2。如果groupby只有一行,我不想将它移动到t2。如何在psql中表达这种类型的更新?

e.g。当前t1:

| a | b | c | d |
|---|---|---|---|
|'m'|'q'|'w'|1  |
|'m'|'q'|'w'|2  |
|'m'|'q'|'w'|3  |
|'m'|'r'|'x'|1  |
|'m'|'r'|'x'|2  |
|'m'|'s'|'y'|1  |

运行更新后所需的t1:

| a | b | c | d |
|---|---|---|---|
|'m'|'q'|'w'|1  |
|'m'|'r'|'x'|1  |
|'m'|'s'|'y'|1  |

运行更新后所需的t2:

| a | b | c | d |
|---|---|---|---|
|'m'|'q'|'w'|2  |
|'m'|'q'|'w'|3  |
|'m'|'r'|'x'|2  |

2 个答案:

答案 0 :(得分:1)

select t.*
from t1 as t
join 
(
select a
    , b
    , c
    , min(d) as min_d
    , count(*) as count
from t1
group by 1,2,3
) x
on t.a = x.a
and t.b = x.b
and t.c = x.c
and t.d != x.min_d
and x.count > 1

答案 1 :(得分:0)

以下是完成更新的最终结果:

with new_t1 as
(
    delete from t1 where (a, b, c, d) in
    (
        select t.a, t.b, t.c, t.d from t1 as t
        join(
            select a,
                   b,
                   c,
                   min(d) as min_d,
                   count(*) as count
            from t1 group by a, b, c
        ) j
        on t.a = j.a
        and t.b = j.b
        and t.c = j.c
        and t.d > j.min_d
    )
    returning *
)
insert into t2 select * from new_t1;