[英]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.