Skip to content
Advertisement

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:

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:

What am I missing? How can I construct my Query to accomplish this task?

Thanks for looking into this 😉

Advertisement

Answer

If you want to add this to all rows, use a window function. One method is:

If you just want one row per tickerid, you can use aggregation:

The logic here is that the first “Buy” id is compared to the first “id”. If they are the same, you have a “Long” trade.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement