根据 MySQL 中的最低 ID 和外键定义位置
Define Position based on lowest ID and Foreign Key in MySQL
我目前面临以下问题:我的 1 Table 经纪人交易数据与此类似:
TickerId Id Ticker Shares OrderType
... ... ... ... ...
01.01.20 ABC 5 ABC 500 Buy
01.01.20 ABC 6 ABC 250 Sell
01.01.20 ABC 7 ABC 250 Sell
... ... ... ... ...
目标是说如果第一个 OrderType(TradeId 相同的最低 Id)是买入,这是一个多头交易,否则是一个空头交易......输出应该是这样的:
TickerId Position Ticker Volume (=SUM(Shares))
... ... ... ...
01.01.20 ABC Long ABC 1000
... ... ... ...
我错过了什么?我怎样才能构建我的查询来完成这个任务?
感谢您对此进行调查 ;)
如果要将此添加到所有行,请使用 window 函数。一种方法是:
select t.*,
(case when first_value(orderType) over (partition by tickerid order by id) = 'Buy'
then 'Long' else 'Short'
end) as position
from t;
如果您只需要每个 tickerid
一行,您可以使用聚合:
select tickerid,
(case when min(case when orderType = 'Buy' then id end) = min(id)
then 'Long' else 'Short'
end) as position
from t
group by tickerid;
这里的逻辑是将第一个“Buy”id 与第一个“id”进行比较。如果它们相同,则您进行了“多头”交易。
我目前面临以下问题:我的 1 Table 经纪人交易数据与此类似:
TickerId Id Ticker Shares OrderType
... ... ... ... ...
01.01.20 ABC 5 ABC 500 Buy
01.01.20 ABC 6 ABC 250 Sell
01.01.20 ABC 7 ABC 250 Sell
... ... ... ... ...
目标是说如果第一个 OrderType(TradeId 相同的最低 Id)是买入,这是一个多头交易,否则是一个空头交易......输出应该是这样的:
TickerId Position Ticker Volume (=SUM(Shares))
... ... ... ...
01.01.20 ABC Long ABC 1000
... ... ... ...
我错过了什么?我怎样才能构建我的查询来完成这个任务?
感谢您对此进行调查 ;)
如果要将此添加到所有行,请使用 window 函数。一种方法是:
select t.*,
(case when first_value(orderType) over (partition by tickerid order by id) = 'Buy'
then 'Long' else 'Short'
end) as position
from t;
如果您只需要每个 tickerid
一行,您可以使用聚合:
select tickerid,
(case when min(case when orderType = 'Buy' then id end) = min(id)
then 'Long' else 'Short'
end) as position
from t
group by tickerid;
这里的逻辑是将第一个“Buy”id 与第一个“id”进行比较。如果它们相同,则您进行了“多头”交易。