【问题标题】:postgresql join and insertpostgresql 加入和插入
【发布时间】:2017-10-11 10:35:38
【问题描述】:

我有两个表,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 列中。

【问题讨论】:

    标签: mysql postgresql join insertion-order


    【解决方案1】:

    尝试更新,而不是插入:

    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
    

    更新协调您的 cmets,将其包装起来以供函数使用

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

    【讨论】:

    • 你能告诉我如何在一个名为 calculate_mrr 的过程中构建它
    • 在 postgresql 程序中...提前致谢
    • 您好,我对此查询有另一个要求,如果accounts_id 还没有出现在汇总表中,那么该查询也需要插入到汇总表中,那么accounts_id 和mrr 都应该作为新记录插入
    • 您好,请考虑一下必须做的事情,当您觉得自己理解任务时,请在 Google 上寻求解决方案。如果没有找到,请点击“提问”按钮并将问题发布到社区
    • 我从昨天开始一直在尝试,也用谷歌搜索并尝试了至少 6-7 种不同的方法,但这种方法会出现一个错误
    猜你喜欢
    • 2013-08-27
    • 2012-05-07
    • 1970-01-01
    • 1970-01-01
    • 2016-08-29
    • 2011-08-30
    • 2019-11-20
    • 1970-01-01
    相关资源
    最近更新 更多