左连接计算值
left join with calculated value
我有一个 table 'users' 和另一个 table 'positions',每个用户股票头寸(代码、股票和价格)各占一行。我想知道每个用户的投资组合的价值,即他们的头寸总和(股票 * 价格)。
示例:
用户 table
user_id, user_name
1, bob
2, steve
职位table
position_id, user_id, symbol, shares, price
1, 1, aapl, 100, 119.50
2, 1, ibm, 200, 155.32
3, 2, goog, 100, 660.05
我希望输出为:
user_name, portfolio_value
bob, 43014
steve, 66005
(其中 43014 = 119.50*100 + 155.32*200)
我确定有一个左连接可以计算每个头寸值(股票 * 价格),然后按用户和组对它们求和,但我是 mysql 的新手。提前谢谢你。
您需要做的第一件事是将头寸转换为投资组合价值。这可以通过以下方式完成:
select user_id, sum(shares * price) as portfolio_value
from portfolio
group by user_id
这可以连接到名称为 table 的用户:
select user_name, portfolio_value
from users
inner join (
select user_id, sum(shares * price) as portfolio_value
from portfolio
group by user_id
) as values
on users.user_id = values.user_id
联接(LEFT、RIGHT、INNER)与此无关。在这种情况下,LEFT JOIN 表示 "Give me all rows from table USERS even if they don't have a row in table portfolios"。您可以阅读有关联接 here 的信息。您的查询将如下所示。
SELECT u.user_name, SUM(p.price*p.shares) AS portfolio_value
FROM users u
LEFT JOIN positions p ON u.user_id = p.user_id
GROUP BY u.user_name
我有一个 table 'users' 和另一个 table 'positions',每个用户股票头寸(代码、股票和价格)各占一行。我想知道每个用户的投资组合的价值,即他们的头寸总和(股票 * 价格)。
示例: 用户 table
user_id, user_name
1, bob
2, steve
职位table
position_id, user_id, symbol, shares, price
1, 1, aapl, 100, 119.50
2, 1, ibm, 200, 155.32
3, 2, goog, 100, 660.05
我希望输出为:
user_name, portfolio_value
bob, 43014
steve, 66005
(其中 43014 = 119.50*100 + 155.32*200)
我确定有一个左连接可以计算每个头寸值(股票 * 价格),然后按用户和组对它们求和,但我是 mysql 的新手。提前谢谢你。
您需要做的第一件事是将头寸转换为投资组合价值。这可以通过以下方式完成:
select user_id, sum(shares * price) as portfolio_value
from portfolio
group by user_id
这可以连接到名称为 table 的用户:
select user_name, portfolio_value
from users
inner join (
select user_id, sum(shares * price) as portfolio_value
from portfolio
group by user_id
) as values
on users.user_id = values.user_id
联接(LEFT、RIGHT、INNER)与此无关。在这种情况下,LEFT JOIN 表示 "Give me all rows from table USERS even if they don't have a row in table portfolios"。您可以阅读有关联接 here 的信息。您的查询将如下所示。
SELECT u.user_name, SUM(p.price*p.shares) AS portfolio_value
FROM users u
LEFT JOIN positions p ON u.user_id = p.user_id
GROUP BY u.user_name