股票K线统计,各个分钟线,日线,周线统计,sql示例

时间:2022-05-14 20:51:30

–k线月线统计
select
Datename(MONTH,CreateTime) mm,Convert(varchar,dateadd(ms,-3,DATEADD(mm,DATEDIFF(m,0,CreateTime)+1,0)),23) monthLastDay,
MAX([SalePrice]) heightPrice,MIN([SalePrice] ) minPrice,
(select top 1 [SalePrice] from [orde_BuyOrderDetails] where Datename(MONTH,CreateTime)=Datename(MONTH,m.CreateTime) order by [CreateTime] asc) openPrice,
(select top 1 [SalePrice] from [orde_BuyOrderDetails] where Datename(MONTH,CreateTime)=Datename(MONTH,m.CreateTime) order by [CreateTime] desc) closePrice,
sum(BuyQuantity) num
from orde_BuyOrderDetails m
group by Datename(MONTH,CreateTime),Convert(varchar,dateadd(ms,-3,DATEADD(mm,DATEDIFF(m,0,CreateTime)+1,0)),23)

–K线周线
select
Datename(WEEK,CreateTime) wk,Convert(varchar,DATEADD(DAY,Datename(WEEK,CreateTime)*7,DATENAME(YEAR,CreateTime)+’-01-01’),23) weekLastDay,
MAX([SalePrice]) heightPrice,MIN([SalePrice] ) minPrice,
(select top 1 [SalePrice] from [orde_BuyOrderDetails] where Datename(WEEK,CreateTime)=Datename(WEEK,m.CreateTime) order by [CreateTime] asc) openPrice,
(select top 1 [SalePrice] from [orde_BuyOrderDetails] where Datename(WEEK,CreateTime)=Datename(WEEK,m.CreateTime) order by [CreateTime] desc) closePrice,
sum(BuyQuantity) num
from (select * from orde_BuyOrderDetails where DATEDIFF(day,CreateTime,’2017-07-05’)<=0) m
group by Datename(WEEK,CreateTime),Convert(varchar,DATEADD(DAY,Datename(WEEK,CreateTime)*7,DATENAME(YEAR,CreateTime)+’-01-01’),23)

–k线日线
SELECT max([SalePrice]) heightPrice,min([SalePrice]) minPrice,sum([BuyQuantity]) num
,(select top 1 [SalePrice] from [orde_BuyOrderDetails] where Convert(varchar,[CreateTime],23)=Convert(varchar,m.[CreateTime],23) order by [CreateTime] asc) openPrice
,(select top 1 [SalePrice] from [orde_BuyOrderDetails] where Convert(varchar,[CreateTime],23)=Convert(varchar,m.[CreateTime],23) order by [CreateTime] desc) closePrice
,Convert(varchar,[CreateTime],23) [CreateTime]
FROM [orde_BuyOrderDetails] m
group by Convert(varchar,[CreateTime],23)
order by [CreateTime]

–查询K线,按分钟分组,(Datename(minute,CreateTime)/5这里的5表示5分钟线,如果是15分钟线就将5替换为15
select [id],
CreateTime,
(Datename(minute,CreateTime)/5 as typeGp,
BuyQuantity,[SalePrice]
from orde_BuyOrderDetails where CONVERT(varchar,CreateTime,23)>=CONVERT(varchar,’2017-07-05’,23)

–查询K线,按分钟分组(推荐写法),typeGp这么长是为了保证分组不会重复,影响统计数据正确性
select [id],
CreateTime,
((Datename(minute,CreateTime)/5+Datename(DAY,CreateTime)1 Datename(MONTH,CreateTime)) * Datename(HOUR,CreateTime)) as typeGp,
BuyQuantity,[SalePrice]
from orde_BuyOrderDetails where CONVERT(varchar,CreateTime,23)>=CONVERT(varchar,’2017-07-05’,23)