SQL PnL 库存查询
我有一个包含交易列表的表:
Security ; Quantity ; Price ; Consid
1. IBM ; +1,000 ; 20 ; -20k
2. IBM ; +2,000 ; 22 ; -44k
3. IBM ; -1,000 ; 30 ; +30k
4. IBM ; -2,000 ; 20 ; +40k
5. IBM ; -2,000 ; 20 ; -20k
因此,PnL 基本上是 Consid 列的总和,因此在添加 Trade#5 之前,PnL 将为 +6k。
添加第 5 笔交易后,盈亏显示为 -14k,这并不能真正反映我们的立场。
我想要的是某种方法来过滤掉未关闭的交易?因此,只有当我们将 2000 股 IBM 股票的购买添加到表中时,交易 #5 才会被允许计入总和。
我最初的尝试是:
set @Ret = @Ret + isnull((SELECT SUM(GC) AS GS
FROM (SELECT SUM(GrossConsid) * - 1 AS GC
FROM Trades AS CT
WHERE (SpecialCond = 'Prop') AND (SettType <> 'Futures') AND (TrdDt <= @Date) AND (TrdDt >=@StartDate) AND (Name = 'my_Comp')
GROUP BY ABS(Quantity)
HAVING (SUM(Quantity) = 0)) AS dt),0)
但我没有发现存在一个边缘条件,即如果我的交易数量为 +5,+5,-5,则不会被计算在内,因为 (SUM( Quantity) = 0))
计算结果为 false。
关于如何纠正这个问题有什么想法吗?
谢谢克里斯
I have a table containing a list of trades:
Security ; Quantity ; Price ; Consid
1. IBM ; +1,000 ; 20 ; -20k
2. IBM ; +2,000 ; 22 ; -44k
3. IBM ; -1,000 ; 30 ; +30k
4. IBM ; -2,000 ; 20 ; +40k
5. IBM ; -2,000 ; 20 ; -20k
So the PnL is basically the sum of the Consid column so before Trade#5 was added the PnL would be +6k.
After Trade #5 was added this shows the PnL as -14k which isnt really that reflective of where we stand.
What I would like is some way of filtering out the not closed trades? So Trade#5 will only be allowed into the sum when we have added a purchase of 2k IBM shares to the table.
My intial attempt at this was:
set @Ret = @Ret + isnull((SELECT SUM(GC) AS GS
FROM (SELECT SUM(GrossConsid) * - 1 AS GC
FROM Trades AS CT
WHERE (SpecialCond = 'Prop') AND (SettType <> 'Futures') AND (TrdDt <= @Date) AND (TrdDt >=@StartDate) AND (Name = 'my_Comp')
GROUP BY ABS(Quantity)
HAVING (SUM(Quantity) = 0)) AS dt),0)
but I have no figured out that there is an edge condition where by if I have a trades with a Quantity of +5,+5,-5 it doesnt get counted because the (SUM(Quantity) = 0))
evaluates to false.
Any ideas on how I can rectify this?
Thanks Chris
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
可运行示例
Runnable Example
您可以让您的应用程序在附加的“已关闭”列中设置一个标志,而不是使用 SQL 来匹配您的库存吗?然后你可以这样做:
Rather than using SQL to match up your inventory, can you have your app set a flag in an additional "Closed" column? Then you could do this:
不能说你的逻辑,只是修正你所说的错误:
Cant say about your logic, just fixing what you say is wrong: