【发布时间】:2016-07-26 15:03:58
【问题描述】:
我想用 TSQL 通过 LIFO(后进先出)方法进行计算。
使用后进先出法将要求您通过卖出最后一笔交易来计算盈亏。
举例说明:
- 交易于 3 月 1 日结束,我们以每只 5 美元的价格购买 10 只股票
- 交易于 3 月 2 日结束,我们以每只 6 美元的价格购买 15 只股票
- 交易于 3 月 3 日结束,我们以每只 4 美元的价格购买 5 只股票
- 交易于 3 月 4 日完成,我们以每只 7 美元的价格出售 17 只股票
到第 4 次交易时,我们现在已经卖出了 3 月 3 日的 5 只股票,每只 4 美元,以及 3 月 2 日的 12 只股票,每只 6 美元。
所以现在我们留下了以下内容: 3 月 1 日交易的 10 只股票,每只 5 美元 3 支股票,每支 6 美元起,于 3 月 2 日交易 (17-5-15 = -3)。
剩余 13 只股票,平均价格为 (10*5 + 3*6) / 13 = 5.23076923
这里是测试数据生成脚本:
use TestTask
go
IF OBJECT_ID('testtable','U')IS NOT NULL
DROP TABLE testtable
go
create table testtable
(
stockid int not null,
dealid int identity (1,1) not null,
dealtype char(1) not null,
stockdate datetime not null,
stockamount int not null,
priceperstock int not null
)
insert into testtable(stockid,dealtype,stockdate,stockamount,priceperstock)
VALUES
(111,'B','01.03.2016',10,5),
(111,'B','02.03.2016',15,6),
(111,'B','03.03.2016',5,4),
(111,'S','04.03.2016',17,7)
我想计算财务状况和许多其他参数,这些参数需要我知道还剩多少合适价格的股票。到目前为止,我已经做到了这一点:
select
stockid,
dealid,
dealtype,
stockdate,
priceperstock,
case dealtype
when 'B' then stockamount
when 'S' then -stockamount
end as stockamount,
sum(
case dealtype
when 'B' then stockamount
when 'S' then -stockamount
end
) over (partition by
stockid order by dealid ROWS UNBOUNDED PRECEDING)
as poistion
from testtable
输出:
stockid dealid dealtype stockdate priceperstock stockamount poistion
111 1 B 2016-01-03 00:00:00.000 5 10 10
111 2 B 2016-02-03 00:00:00.000 6 15 25
111 3 B 2016-03-03 00:00:00.000 4 5 30
111 4 S 2016-04-03 00:00:00.000 7 -17 13
期望的输出:
stockid dealid dealtype stockdate priceperstock stockamount poistion stocksleft
111 1 B 2016-01-03 00:00:00.000 5 10 10 10
111 2 B 2016-02-03 00:00:00.000 6 15 25 3
111 3 B 2016-03-03 00:00:00.000 4 5 30 0
111 4 S 2016-04-03 00:00:00.000 7 -17 13 0
最好的方法是什么?
【问题讨论】:
标签: sql tsql sql-server-2012 sql-scripts lifo