我正在尝试将两个表加在一起,然后从另一个中减去一个。通过查询,我可以将两个表加在一起,但不能将它们相减。这是在 Postgres 中尝试的,下面是表格:
memberid ticker numshares purchasedate transactionid purchaseprice
7 aapl 1 Jun 28, 2017 22 146
7 aapl 1 Jun 28, 2017 23 146
7 hog 1 Jun 28, 2017 24 55
7 aapl 10 Jun 28, 2017 25 1458
7 aapl 2 Jun 28, 2017 26 292
7 aapl 3 Jun 28, 2017 27 437
7 aapl 5 Jun 28, 2017 28 729
这是销售表:
memberid ticker numshares selldate sellid sellprice
7 aapl 10 Jun 28, 2017 4 1458
7 aapl 15 Jun 29, 2017 5 2154
更新:除了一个细节之外,我已经完成了所有工作 Postgres 声明:
`select qbuys.ticker, qbuys.total_purchaseprice-qsells.total_sellprice
as current_total, qbuys.total_purchaseshares-qsells.total_sellshares as
current_shares
from
(select sells.ticker, sum(numshares) as total_sellshares,
sum(sellprice) as total_sellprice
from sells
where memberid = 7
group by ticker) as qsells, (select stocks.ticker, sum(numshares) as
total_purchaseshares, sum(purchaseprice) as total_purchaseprice from
stocks
where memberid = 7
group by ticker) as qbuys
where qbuys.ticker=qsells.ticker`
剩下的唯一问题是,这不会退回没有相应销售的购买。如果每个表中有相同代码的买入和卖出,它只会吐出总数。所以我需要的更新是让这个吐出没有相应销售的购买。
最佳答案
您需要连接两个表以便从一列中减去另一列的总和。
SELECT
a.ticker
,sum(a.numshares) as Total_Sell_Shares
,sum(a.sellprice) as Total_Sell_Price
,sum(a.numshares) - sum(b.numshares) as Total_Shares
,sum(a.sellprice) - sum(b.purchaseprice) as Total_Price
FROM Sells A
JOIN Stocks B on a.ticker = b.ticker
GROUP BY a.ticker
关于sql - 我试图对两个表求和,然后从另一个表中减去一个表。 H,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44830408/