如何汇总OHLC数据的价格

时间:2017-06-06 19:25:53

标签: sql sql-server

我有一个带有列的SQL Server表:

ID, START_DTTM, OPEN, HIGH, LOW, CLOSE

我必须每小时汇总数据。

所以,我尝试了这个查询:

SELECT
    ID,
    MIN(START_DTTM) START_DTTM,
    MAX(HIGH) AS HIGH,
    MIN(LOW) AS LOW
FROM 
    MY_TABLE
GROUP BY 
    ID, DATEPART(DAY, START_DTTM), DATEPART(HOUR, START_DTTM)

它有效,但我无法拉开和关闭。

我试过这样的事情:

FIRST_VALUE(OPEN_PRICE) OVER (PARTITION BY 
DATEPART(DAY, START_DTTM), DATEPART(HOUR, START_DTTM) ORDER BY START_DTTM)

当然,它不起作用。我该怎么办?

1 个答案:

答案 0 :(得分:0)

您可以使用子查询:

SELECT ID, MIN(START_DTTM) START_DTTM, MAX(HIGH) AS HIGH, MIN(LOW) AS LOW,
       MAX(CASE WHEN seqnum_asc = 1 THEN OPEN_PRICE END) as open_price,
       MAX(CASE WHEN seqnum_desc = 1 THEN CLOSE_PRICE END) as close_price
FROM (SELECT t.*,
             ROW_NUMBER() OVER (PARTITION BY ID, DATEPART(DAY, START_DTTM), DATEPART(HOUR, START_DTTM) ORDER BY STRT_DTTM) as seqnum_asc,
             ROW_NUMBER() OVER (PARTITION BY ID, DATEPART(DAY, START_DTTM), DATEPART(HOUR, START_DTTM) ORDER BY STRT_DTTM) as seqnum_desc
      FROM MY_TABLE
     ) t
GROUP BY ID, DATEPART(DAY, START_DTTM), DATEPART(HOUR, START_DTTM);