簡體   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