postgresql连接和插入
postgresql join and insert
我有两个 table,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。但现在我想把它放在一个现有的 table 命名摘要中,其中已经有列以及 account_id 和 MRR 列是空的。
我想将从查询中获得的 MRR 值放入 MRR 列中,并匹配摘要 table 和 account_subscriptions table 的相应 account_id。
尝试更新,而不是插入:
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 and/or plpgsql - 将代码包装在函数中没有多大意义。里面没有逻辑...
我有两个 table,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。但现在我想把它放在一个现有的 table 命名摘要中,其中已经有列以及 account_id 和 MRR 列是空的。
我想将从查询中获得的 MRR 值放入 MRR 列中,并匹配摘要 table 和 account_subscriptions table 的相应 account_id。
尝试更新,而不是插入:
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 and/or plpgsql - 将代码包装在函数中没有多大意义。里面没有逻辑...