0

我正在运行以下查询以获取投资组合的未平仓头寸:

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

由于别名不能用于计算,我认为我需要使用子查询。我已经尝试了几件事,但无法使其正常工作。

任何人都可以对此有所了解吗?子查询是要走的路吗?还有其他更好的方法吗?

4

1 回答 1

0

不确定您的查询(您似乎正在对 LEFT JOINed 表中的字段执行 GROUP BY,对于未找到的匹配行可能为空),但可能交叉连接到子选择以获得所有价格的总和

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
于 2013-07-08T11:06:52.923 回答