我正在运行以下查询以获得投资组合的未平仓头寸:
SELECT SUM(trades.quantity) as total_quantity, SUM(trades.price) as total_cost, SUM(trades.price)/SUM(trades.quantity) as cost_per_share,
trades.ticker, tickers.code
FROM (trades)
LEFT JOIN tickers
ON trades.ticker = tickers.id
GROUP BY tickers.code
HAVING total_quantity > 0
ORDER BY tickers.code
我想添加一个额外的列来显示一个位置的弱化,即:
total_cost/SUM(total_cost) -- Dividing any given position cost by the total cost of the portfolio
由于别名不能用于计算,我想我需要使用子查询。我尝试过一些东西,但无法使它发挥作用。
有人可以对此有所了解吗?是子查询的方式去?还有其他更好的方法吗?
答案 0 :(得分:0)
您的查询不确定(您似乎在LEFT JOINed表的字段上执行GROUP BY,对于未找到的匹配行可能为null),但可能交叉连接到子选择以获取所有匹配行的总数价格
SELECT total_quantity, total_cost, cost_per_share, trades.ticker, tickers.code, total_cost/total_of_prices
FROM
(
SELECT SUM(trades.quantity) as total_quantity, SUM(trades.price) as total_cost, SUM(trades.price)/SUM(trades.quantity) as cost_per_share,
trades.ticker, tickers.code
FROM trades
LEFT JOIN tickers
ON trades.ticker = tickers.id
GROUP BY tickers.code
HAVING total_quantity > 0
) Sub1
CROSS JOIN
(
SELECT SUM(price) as total_of_prices
FROM trades
WHERE quantity > 0
) Sub2
ORDER BY tickers.code