我有下表:
id | underlying | option_symbol | option_type | expiration_date | strike | mid |
我需要对连接字段执行计算,并使用这些计算字段进行进一步排序。
这是对我的意思:
SELECT a.underlying,
a.expiration_date,
(a.strike - b.strike) as spread_profit,
(a.mid - b.mid) as spread_distance,
(spread_distance - spread_profit) as spread_max_loss,
(spread_profit / spread_max_loss) as spread_profit_ratio
FROM option_data a
JOIN option_data b ON a.underlying = b.underlying AND a.expiration_date = b.expiration_date
WHERE a.option_type = 'put'
AND b.option_type = 'call'
AND a.expiration_date <= '2017-10-31'
group by a.underlying, a.expiration_date order by spread_profit_ratio desc
制定此查询的正确方法是什么?
答案 0 :(得分:2)
您必须替换整个表达式,例如
SELECT ...,
(a.strike - b.strike) AS spread_profit,
(a.mid - b.mid) AS spread_distance,
(a.mid - b.mid - a.strike + b.strike) AS spread_max_loss,
((a.strike - b.strike) / (a.mid - b.mid - a.strike + b.strike))
AS spread_profit_ratio
...
同样适用于ORDER BY
子句,但您可以使用快捷方式ORDER BY 6
按第六个SELECT
列表项进行排序。
如果这太麻烦,可以使用子选择:
SELECT underlying,
expiration_date,
spread_profit,
spread_distance,
spread_max_loss,
spread_profit / spread_max_loss AS spread_profit_ratio
FROM (SELECT underlying,
expiration_date,
spread_profit,
spread_distance,
(spread_distance - spread_profit) AS spread_max_loss
FROM (SELECT a.underlying,
a.expiration_date,
(a.strike - b.strike) as spread_profit,
(a.mid - b.mid) as spread_distance
FROM ...
) sub_1
) sub_2
WHERE ...
ORDER BY spread_profit_ratio DESC;
这是你的选择!