-1

我有两个表,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; 

使用此代码,我可以找到作为 MRR 的 total_bill 及其相应的 account_id。但是现在我想把它放在一个名为 summary 的现有表中,其中已经有列以及 account_id 和 MRR 列是空的。

我想将从查询中获得的 MRR 值放入与汇总表和 account_subscriptions 表的相应 account_id 匹配的 MRR 列中。

4

1 回答 1

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 - 只是将代码包装在函数中没有多大意义。里面没有逻辑...

于 2017-05-12T07:45:21.453 回答