我有一个表1,希望在postgres中向表2中插入值。表1是这样的:
Table1:
z a b c
q1 x 10 5
q1 y null 20
q1 y null null
q2 x 20 10
q2 y null 15
q2 y null 25
表1的值应该插入这样的表2中:
Table2:
z b c1 c2
q1 10 20 null
q2 20 15 25
因此,表1.z中的different值应该是表2中的一行。(table2.b=table1.b WHERE table1.a=x((table2.c=table1.c WHERE table1.a=y(
我尽了最大努力让可以理解
这有点古怪,但它是可以做到的。您需要在内部查询中对记录进行排名,然后在外部查询中进行条件聚合:
insert into table2(z, b, c1, c2)
select
z,
max(case when a = 'x' and rnb = 1 then b end),
max(case when a = 'y' and rnc = 1 then c end),
max(case when a = 'y' and rnc = 2 then c end)
from (
select
t.*,
row_number() over(partition by z, a order by b) rnb,
row_number() over(partition by z, a order by c) rnc
from table1 t
) t
group by z
DB Fiddle上的演示:
z|b|c1|c2:-|-:|-:||:q1|10|20|nullq2|20|15|25