我正在运行以下查询以获取投资组合的未平仓头寸:
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
由于别名不能用于计算,我认为我需要使用子查询。我已经尝试了几件事,但无法使其正常工作。
任何人都可以对此有所了解吗?子查询是要走的路吗?还有其他更好的方法吗?