【发布时间】:2017-06-29 16:20:16
【问题描述】:
我正在尝试将两个表相加并从另一个表中减去一个。通过查询,我可以将两个表相加,但无法减去它们。正在 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`
剩下的唯一问题是,这不会返回没有相应销售的购买。只有在每张桌子上都有相同代码的买入和卖出时,它才会吐出总数。所以我需要的更新是让这个没有相应销售的购买吐出。
【问题讨论】:
-
什么问题?你试过这样做吗?它不工作吗?错误是什么?
-
我可以使用与上述 SQL 语句类似的语句将这些表汇总在一起。我无法从购买表中减去销售表。
-
您使用的是哪个 DBMS?后格雷斯?甲骨文?
-
我正在使用 Postgres
-
@JoshuaWilcken 我的意思是,如果您说“我遇到问题”或“我遇到麻烦”,那么您需要告诉我们什么问题是,即:什么都没有发生?你有错误吗?你得到一个结果,但它是错误的?电脑会爆炸吗?在不知道问题是什么的情况下,人们只能推测,这并不能产生有用的线索。
标签: sql postgresql