我正在搜索一个简单的查询,可以将较低时间范围内的库存数据更改为更高的时间范围。考虑下表
Open High Low Close Volume
Date
1999-01-04 10:22:00 1.1801 1.1819 1.1801 1.1817 4
1999-01-04 10:23:00 1.1817 1.1818 1.1804 1.1814 18
1999-01-04 10:24:00 1.1817 1.1817 1.1802 1.1806 12
1999-01-04 10:25:00 1.1807 1.1815 1.1795 1.1808 26
1999-01-04 10:26:00 1.1803 1.1806 1.1790 1.1806 4
1999-01-04 10:27:00 1.1801 1.1801 1.1779 1.1786 23
1999-01-04 10:28:00 1.1795 1.1801 1.1776 1.1788 28
1999-01-04 10:29:00 1.1793 1.1795 1.1782 1.1789 10
1999-01-04 10:31:00 1.1780 1.1792 1.1776 1.1792 12
1999-01-04 10:32:00 1.1788 1.1792 1.1788 1.1791 4
每1分钟更新一次。如何通过查询将其更改为2分钟数据?
答案 0 :(得分:1)
你想要分组:
select floor(time/2) as time,
sum(volume) as volume,
max(case when time = 2*floor(time/2) then open end) as open,
max(high) as high,
max(low) as low),
max(case when time = 2*floor(time/2)+1 then close end) as close
from t
group by floor(time/2)
使用row_number()
可以使打开和关闭的公式更简单,更通用,但您需要指定数据库。
答案 1 :(得分:1)
答案在SQL Server
。因此,您可能希望更改某些语法以适应。就partition check this out.而言。
同时假设您的资产非常有流动性且不会错过一分钟......;)此查询可以进一步改进。请试一试。
查询:[编辑以排除任何来自null的ohlcv值。]
select z.dt, a.opens as o, z.h,
z.l, b.closes as c, z.v
from (
select Dateadd(minute, 1, x.dates) as dt,
max(y.high) as h, min(y.low) as l,
sum(y.volume) as v
from ohlcv x
left join ohlcv y
on y.dates
between x.dates and
Dateadd(minute, 1, x.dates)
where (DATEPART(MINUTE, x.Dates) % 2) = 0
group by Dateadd(minute, 1, x.dates)) z
left join
ohlcv a
on a.dates = Dateadd(minute, -1, z.dt)
left join ohlcv b
on b.dates = z.dt
where not (a.opens is null or z.h is null
or z.l is null or b.closes is null
or z.v is null)
;
结果:
| DT |O |H |L |C | V |
---------------------------------------------------------------------------
| January, 04 1999 10:23:00+0000 | 1.1801 | 1.1819 | 1.1801 | 1.1814 | 22 |
| January, 04 1999 10:25:00+0000 | 1.1817 | 1.1817 | 1.1795 | 1.1808 | 38 |
| January, 04 1999 10:27:00+0000 | 1.1803 | 1.1806 | 1.1779 | 1.1786 | 27 |
| January, 04 1999 10:29:00+0000 | 1.1795 | 1.1801 | 1.1776 | 1.1789 | 38 |
| January, 04 1999 10:31:00+0000 | 1.1781 | 1.1793 | 1.1776 | 1.1792 | 17 |