来自多个表的乘法和加法(简单的股市程序)

时间:2018-10-23 14:44:21

标签: mysql

我有以下3个表格:债券,库存和客户。

股票包含:名称,代码(pk),最新

库存包含:ssn(pk),ticker(pk),金额

客户包含:名称,ssn(pk),资产

我想通过将股票数量乘以股票价值,然后将每个人的资产相加来显示每个人在帐户中的价值。

SELECT Customer.name AS "Customers Name", SUM(amount*latest) + assets AS "Total value"

FROM Customer, Inventory, Stocks

WHERE Inventory.ssn = Customer.ssn AND Stocks.ticker = Inventory.ticker

这仅显示一个人,并且显示了错误的价值量(太高了),我猜代码只是将所有Stocks *最新值相加,然后将其加在一起供一个人使用。

我的预期结果是在同一行中包含客户名称和总值的表,将所有客户显示在一个表中

通过解决此问题

SELECT 
    C.name AS "Customers Name", SUM(I.amount*S.latest) + C.assets AS "Total value"
FROM Customer as C
INNER JOIN Inventory as I on I.ssn = C.ssn
INNER JOIN Stocks    as S on S.ticker = I.ticker
GROUP BY C.name

1 个答案:

答案 0 :(得分:0)

尝试此查询:

SELECT 
    C.name AS "Customers Name", SUM(I.amount*S.latest) + C.assets AS "Total value"
FROM Customer as C
INNER JOIN Inventory as I on I.ssn = C.ssn
INNER JOIN Stocks    as S on S.ticker = I.ticker