CTE , . 12 , , . , , . , .
: http://rextester.com/QDQR73738
:
create table test_data(ticker varchar(5), date integer, tick datetime, cls decimal(10,2), volume integer);
create table test_data2(ticker varchar(5), date integer, tick datetime, cls decimal(10,2), volume integer);
insert into test_data
select 'ASC', 20151231, '1899-12-30 12:30:00', 3453, 2743 union all
select 'ASC', 20151231, '1899-12-30 12:29:00', 3449, 3490 union all
select 'ASC', 20151231, '1899-12-30 12:28:00', 3436, 930 union all
select 'ASC', 20151231, '1899-12-30 12:27:00', 3435, 255 union all
select 'ASC', 20151231, '1899-12-30 12:26:00', 3434, 4 union all
select 'ASC', 20151231, '1899-12-30 12:23:00', 3444.59, 54 union all
select 'BSC', 20151231, '1899-12-30 12:23:00', 3444.59, 54 union all
select 'BSC', 20151231, '1899-12-30 12:28:00', 3436, 930
;
:
Declare @tickers Table (ticker varchar(5));
Insert into @tickers select distinct ticker from test_data;
Declare @ticker varchar(5);
While exists (Select * From @tickers)
BEGIN
select @ticker = min(ticker) from @tickers;
with cte(tm)
as( Select cast('1899-12-30 12:23:00' as datetime) as tm
union all
Select dateadd(minute, 1, tm)
from cte
where tm < cast('1899-12-30 12:31:00' as datetime)
)
insert into test_data2
select
max(ticker) over (partition by grp order by tick rows unbounded preceding) ticker,
max(date) over (partition by grp order by tick rows unbounded preceding) date,
tick,
max(cls) over (partition by grp order by tick rows unbounded preceding) cls,
volume
from (
select
ticker,
date,
tick,
cls,
volume,
id,
max(id1) OVER(ORDER BY tick ROWS UNBOUNDED PRECEDING) AS grp
from (
select
td.ticker,
td.date,
coalesce(td.tick, cte.tm) tick,
td.cls,
coalesce(td.volume, 0) volume,
row_number() over (order by tick) id
from test_data td
right outer join cte
on td.tick = cte.tm
and td.ticker = @ticker
) cte2
CROSS APPLY ( VALUES( CASE WHEN ticker IS NOT NULL THEN id END) )
AS A(id1)
) cte3;
Delete from @tickers where ticker = @ticker;
End
select * from test_data2
order by ticker, tick;