我有以下逐批股票数据:
stock_code,价格,数量,transaction_time
每一行代表一个事务。
我想聚合A股的N行(交易)数,以便:
价格之和*N行以上成交量>= 5,000,000
A类股票的总“块”将包含A类股票的平均价格和总成交量。每个区块应以第一次和最后一次交易的transaction_time为界。
我想加入一个股票B的表,B的行应该在股票A的第一个和最后一个transaction_time之间有transaction_time。

在这个例子中,5,024,675美元的A类股票(0019.HK)在209-09-10年间在01:30:01和01:35:01之间交易。在01:30- 01:35:01,12,500股B股(0087.HK)的平均价格为12.088。
我能够为A类股票生成一个CTE表:
With primary_instrument (ric, price,volume,dollarbar, ttime, index_for_joining)
AS
--ric represents stock code and ttime represents transaction time
--index_for_joining is created by removing millisecond data from ttime
(SELECT ric,price, volume,volume*price,ttime,minutesecindex
FROM [firsttry].[dbo].[swirepacific5] where views='trdprc_1' and inst = 0 and RIC = '0019.HK'
)
SELECT TOP (1000) ric,price, volume,dollarbar,
SUM(dollarbar) OVER (ORDER BY ttime ROWS BETWEEN UNBOUNDED PRECEDING and CURRENT ROW) as CUMSUM,
ttime,index_for_joining
from primary_instrument并为二级股票生成CTE表:
With secondary_instrument (ric, price,volume, index_for_joining)
AS
(SELECT ric,price, volume,minutesecindex
FROM [firsttry].[dbo].[swirepacific5] where views='trdprc_1' and inst = 0 and RIC = '0087.HK'
)
SELECT TOP (1000) * from secondary_instrument我的问题是:
滴答数据、两个表的输出和“数据块”可以从下面的excel文件下载:https://www.dropbox.com/s/zufrp1giaoi4hfg/stockdata.xlsx?dl=0。
发布于 2020-05-12 12:23:53
我将首先回答第二个问题,同时意识到手头的问题可能有些复杂,难以过关。为了限制ttime/index_for_joining列值上的时间框架,可以将多个定义放在单个With语句下,用逗号(,)分隔。
因此,在您的情况下,如果您需要访问index_for_joining列(如果我没有错的话),它是帮助从滴答数据中提取时间帧的时间戳,您可以将secondary_instrument CTE与primary_instrument放在一起,并在时间范围匹配的条件下将两者连接起来(下面我已经将它们作为外键加入了RIC,但是没有什么可以阻止您在联接条件下扩展它们)。
With primary_instrument (
ric
, price
, volume
, dollarbar
, ttime
, index_for_joining
) AS (
Select ric
, price
, volume
, volume * price
, ttime
, minutesecindex
From [firsttry].[dbo].[swirepacific5]
Where views = 'trdprc_1'
And inst = 0
And RIC = '0019.HK'
),
secondary_instrument (
ric
, price
, volume
, index_for_joining
) AS (
SELECT ric
, price
, volume
, minutesecindex
From [firsttry].[dbo].[swirepacific5]
Where views = 'trdprc_1'
And inst = 0
And RIC = '0087.HK'
) Select Top (1000)
ric
, price
, volume
, dollarbar
, SUM(dollarbar) OVER (
ORDER BY ttime ROWS BETWEEN UNBOUNDED PRECEDING and CURRENT ROW
) As CUMSUM
, ttime
, index_for_joining
, secondary_instrument.*
From primary_instrument
Inner Join
secondary_instrument
On primary_instrument.ric = secondary_instrument.ric
;关于第一个问题--除非您有办法分割卷并将它们放在一起,否则我看到的唯一选择是编写另一个递归的CTE,以处理从第一个滴答到当前行的价格总和,并使用where子句来限制总和(Sql Server支持分区子句的范围和行--但这里需要的是单个合同价格,以便能够平分滴答,并尽可能接近定义的上限--500万)。请记住,这种查询是一个代价高昂的过程,首先是因为它的CTE,其次是因为每个返回的记录都需要计算所有以前记录的价格之和。这就是说,除非您引入一个新列,并在新的滴答出现时保留该值。
https://stackoverflow.com/questions/61382516
复制相似问题