简体   繁体   English

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

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

I am currently facing the following issue: I have 1 Table with my Broker Trading Data similar to this:我目前面临以下问题:我有 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
...           ...  ...      ...     ...

The Goal is to say IF first OrderType (lowest Id where TradeId is the same) was a Buy, it's a LONG Trade ELSE a Short Trade ... output should be like this:目标是说如果第一个 OrderType(TradeId 相同的最低 Id)是一个买入,它是一个多头交易 ELSE 一个空头交易......输出应该是这样的:

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

What am I missing?我错过了什么? How can I construct my Query to accomplish this task?如何构建我的查询来完成此任务?

Thanks for looking into this ;)感谢您查看这个 ;)

If you want to add this to all rows, use a window function.如果要将其添加到所有行,请使用窗口函数。 One method is:一种方法是:

select t.*,
       (case when first_value(orderType) over (partition by tickerid order by id) = 'Buy'
             then 'Long' else 'Short'
        end) as position
from t;

If you just want one row per tickerid , you can use aggregation:如果您只想要每个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;

The logic here is that the first "Buy" id is compared to the first "id".这里的逻辑是将第一个“购买”id 与第一个“id”进行比较。 If they are the same, you have a "Long" trade.如果它们相同,则您进行“多头”交易。

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

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