合并两个表并在 PostgreSQL 中计算加权和
Merging two tables and calculating weighted sum in PostgreSQL
我有以下两个table:
表 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 和类别合并两个 table。但是想计算金额上的加权和。条件是,如果我有相同的 shopid、hour、category 那么它将执行加权和。否则,它将保留来自 table1 和 table2 的原始数据。合并后,table 看起来像这样:
合并表
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.
...................................
知道怎么做吗?
嗯。你似乎想要一个 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)
我有以下两个table:
表 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 和类别合并两个 table。但是想计算金额上的加权和。条件是,如果我有相同的 shopid、hour、category 那么它将执行加权和。否则,它将保留来自 table1 和 table2 的原始数据。合并后,table 看起来像这样:
合并表
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.
...................................
知道怎么做吗?
嗯。你似乎想要一个 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)