Postgresql如何跨两个不同的表求和?
我有两张桌子:Postgresql如何跨两个不同的表求和?,sql,postgresql,Sql,Postgresql,我有两张桌子: |currency_type|user_id|amount| |-------------|-------|------| | aaa| 404| 2000| | bbb| 404| 300| | ccc| 22| 444| 如何分别获得每种货币类型的两个表(金额+余额)的总和?用户id=404的结果示例 性能对我来说很重要,所以越快越好 |currency_type|user_id| s
|currency_type|user_id|amount|
|-------------|-------|------|
| aaa| 404| 2000|
| bbb| 404| 300|
| ccc| 22| 444|
如何分别获得每种货币类型的两个表(金额+余额)的总和?用户id=404的结果示例
性能对我来说很重要,所以越快越好
|currency_type|user_id| sum|
|-------------|-------|-------|
| aaa| 404| 2030|
| bbb| 404| 300|
| xxx| 404| 50|
试试这个:
create table t1 (currency_type text,user_id int,amount int);
create table t2 (currency_type text,user_id int,balance int);
insert into t1 values
('aaa', 404, 2000),
('bbb', 404, 300),
('ccc', 22, 444);
insert into t2 values
('aaa', 404, 30),
('xxx', 404, 50);
with t1t2 as (
select currency_type, user_id, amount from t1
union all
select currency_type, user_id, balance as amount from t2
)
select currency_type, user_id, sum(amount)
from t1t2
where user_id = 404
group by currency_type, user_id
结果
货币类型|用户id |总和
:------------ | ------: | ---:
aaa | 404 | 2030
bbb | 404 | 300
xxx | 404 | 50
示例
解释
只需合并两个表,但在查询中暂时将余额重命名为amount。现在,余额和金额在同一张表中。剩下的就是每个货币类型/用户id组合的合计金额列
create table t1 (currency_type text,user_id int,amount int);
create table t2 (currency_type text,user_id int,balance int);
insert into t1 values
('aaa', 404, 2000),
('bbb', 404, 300),
('ccc', 22, 444);
insert into t2 values
('aaa', 404, 30),
('xxx', 404, 50);
with t1t2 as (
select currency_type, user_id, amount from t1
union all
select currency_type, user_id, balance as amount from t2
)
select currency_type, user_id, sum(amount)
from t1t2
where user_id = 404
group by currency_type, user_id
currency_type | user_id | sum
:------------ | ------: | ---:
aaa | 404 | 2030
bbb | 404 | 300
xxx | 404 | 50