我有两个表,account_subscriptions和order_item,我写了这个查询:
Select a1.accounts_id,sum(a2.quantity * a2.unit_price) as MRR
from account_subscriptions a1
inner join order_item a2 on a1.subscription_id = a2.account_subscriptions_id
group by a1.accounts_id;
使用此代码,我可以找到total_bill作为MRR及其相应的account_id。但是现在我想将它放在一个名为summary的现有表中,其中已经有一些列以及account_id和MRR列为空。
我想将我从查询中得到的MRR值放入MRR列,并与summary table和account_subscriptions表的相应account_id相匹配。
答案 0 :(得分:0)
尝试更新,而不是插入:
with c as (
Select a1.accounts_id,sum(a2.quantity * a2.unit_price) as MRR
from account_subscriptions a1
inner join order_item a2 on a1.subscription_id = a2.account_subscriptions_id
group by a1.accounts_id
)
update summary s set MRR = c.MRR
from c
where c.accounts_id = s.accounts_id
更新核对您的评论,并将其打包为功能使用
create function fn_name_here() returns int as
$$
begin
with c as (
Select a1.accounts_id,sum(a2.quantity * a2.unit_price) as MRR
from account_subscriptions a1
inner join order_item a2 on a1.subscription_id = a2.account_subscriptions_id
group by a1.accounts_id
)
update summary s set MRR = c.MRR
from c
where c.accounts_id = s.accounts_id;
return 0;
end;
$$ language plpgsql
;
请开始阅读和练习SQL和/或plpgsql - 只是将代码包装在函数中没有多大意义。内部没有逻辑......