查询以从两个表中检索值的总和

时间:2018-03-27 20:49:07

标签: sql

我有以下两个表

----------------------------
| name       | nationality |
----------------------------
| Manuel     | Spanish     |
| Juan       | Spanish     |
| Marye      | Dutch       |
| Liza       | Dutch       |
| John       | English     |
| Mr. Stingy | Stingish    |
----------------------------

交易

--------------------------------
| id | seller | buyer  | value |
--------------------------------
| 1  | Marye  | Juan   |   100 |
| 2  | John   | Manuel |    30 |
| 3  | John   | Manuel |    50 |
| 4  | John   | Marye  |    10 |
| 5  | Juan   | Lisa   |    30 |
--------------------------------

我想查询一下我检索每个国籍买入和卖出的价值。所以输出将是这样的:

--------------------------------
| nationality | bought  | sold |
--------------------------------
| Spanish     |     180 |   30 |
| Dutch       |      40 |  100 |
| English     |       0 |   90 |
| Stingish    |       0 |    0 |
--------------------------------

但我无法在一个查询中完成它,

我可以这样做:

SELECT persons.nationality, 
IFNULL(sum(trades.value), 0) as bought 
FROM trades 
RIGHT JOIN persons 
ON trades.buyer = persons.name 
GROUP BY nationality

获取已购买的列和已售出列的相同步骤

SELECT persons.nationality, 
IFNULL(sum(trades.value), 0) as sold 
FROM trades 
RIGHT JOIN persons 
ON trades.seller = persons.name 
GROUP BY nationality

但是,我无法一次性得到它,任何提示?

1 个答案:

答案 0 :(得分:3)

这应该相当容易。你可能会过度思考它。

SELECT 
p.nationality, 
ISNULL(SUM(sell.value), 0) AS sold, 
ISNULL(SUM(buy.value),0) AS bought

FROM persons p
LEFT JOIN trades sell
ON p.name = sell.seller
LEFT JOIN trades buy
ON p.name = buy.buyer

GROUP BY p.nationality