【问题标题】:Merging two tables and calculating weighted sum in PostgreSQL在PostgreSQL中合并两个表并计算加权和
【发布时间】:2019-12-19 11:41:45
【问题描述】:

我有以下两张表:

表1

 shopid  hour      category  amount
    ------------------------------------
    1        7          food       10
    1        8          food       15
    1        10         misc.      5
    ...................................

表2

 shopid  hour      category  amount
    ------------------------------------
    1        7          food       30
    1        8          food       10
    1        9          misc.      10
    ...................................

现在,我想根据它们的 shopid、event_hour 和类别合并这两个表。但是要计算金额上的加权和。条件是,如果我有相同的 shopid、小时、类别,那么它将执行加权和。否则,它将保留 table1 和 table2 中的原始数据。合并后的表格如下所示:

合并表

shopid  hour      category  amount
------------------------------------
1        7          food       25   //amount= table1.amount*0.25+ table2.amount*0.75
1        8          food       11.25 //amount= table1.amount*0.25+ table2.amount*0.75
1        9          misc.      10   //this amount remains same as at hour 9 nothing was on table1.
1        10         misc.      5    //this amount remains same as at hour 10 nothing was on table2.
...................................

任何线索如何做到这一点?

【问题讨论】:

    标签: sql postgresql union-all


    【解决方案1】:

    嗯。你似乎想要一个full join 和算术:

    select shopid, hour, category,
           (case when t1.shopid is null then t2.amount
                 when t2.shopid is null then t1.amount
                 else t1.amount * 0.25 + t2.amount * 0.75
            end) as weighted_sum
    from table1 t1 full join
         table2 t2
         using (shopid, hour, category)
    

    【讨论】:

      猜你喜欢
      • 2018-12-24
      • 2012-12-13
      • 2014-03-15
      • 2017-10-31
      • 2015-09-04
      • 2022-01-12
      • 1970-01-01
      • 1970-01-01
      • 2013-03-28
      相关资源
      最近更新 更多