繁体   English   中英

Postgresql 如何跨两个不同的表求和?

[英]Postgresql how to sum across two different tables?

我有两张桌子:

|currency_type|user_id|amount|
|-------------|-------|------|
|          aaa|    404|  2000|
|          bbb|    404|   300|
|          ccc|     22|   444|
|currency_type|user_id|balance|
|-------------|-------|-------|
|          aaa|    404|     30|
|          xxx|    404|     50|

我怎样才能分别为每个currency_type获得两个表的总和(金额+余额)? user_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

例子

https://dbfiddle.uk/?rdbms=postgres_11&fiddle=89c7d5b9ee8d5ce1eb42ee5cda961d0c

解释

只需合并两个表,但在查询中将余额重命名为金额。 现在,您将在同一个表中拥有余额和金额。 剩下的就是每个 currency_type/user_id 组合的金额列的总和。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM