股票K線統計,各個分鐘線,日線,周線統計,sql示例
資料庫是sqlserver
–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)