繁体   English   中英

根据 MySQL 中的最低 ID 和外键定义位置

[英]Define Position based on lowest ID and Foreign Key in MySQL

我目前面临以下问题:我有 1 个表,其中包含与此类似的经纪商交易数据:

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)是一个买入,它是一个多头交易 ELSE 一个空头交易......输出应该是这样的:

TickerId       Position   Ticker   Volume (=SUM(Shares))
...            ...        ...      ...
01.01.20 ABC   Long       ABC      1000
...            ...        ...      ...

我错过了什么? 如何构建我的查询来完成此任务?

感谢您查看这个 ;)

如果要将其添加到所有行,请使用窗口函数。 一种方法是:

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;

这里的逻辑是将第一个“购买”id 与第一个“id”进行比较。 如果它们相同,则您进行“多头”交易。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM