使用PostgreSQL创建股票图表

时间:2019-03-01 19:31:15

标签: postgresql

我正在尝试使用将类似于以下内容的postgreSQL制作这些股票图表之一。

stock chart

我的数据如下所示:

stock_data    
stock_price   trade_datetime
5.1         | 1/1/2000 1:00 PM
6.2         | 1/1/2000 2:00 PM
5.0         | 1/2/2000 1:00 PM
3.4         | 1/2/2000 2:00 PM
4.8         | 1/2/2000 3:00 PM
7.0         | 1/3/2000 2:30 PM
5.9         | 1/3/2000 5:55 PM

所需结果

MIN | MAX | AVG | close | date
5.1 | 6.2 | 5.65| 6.2   | 1/1/2000
3.4 | 5.0 | 4.4 | 4.8   | 1/2/2000
5.9 | 7.0 | 6.45| 5.9   | 1/3/2000

我想我可能需要使用窗口函数,但是似乎无法正确地做到这一点。

1 个答案:

答案 0 :(得分:2)

您可以通过使用预期的聚合函数,然后加入使用LAST_VALUE窗口函数的派生表来完成此操作:

SELECT
    MIN(stock_price) AS "MIN"
    , MAX(stock_price) AS "MAX"
    , AVG(stock_price) AS "AVG"
    , MAX(closing.closing_price) AS "close"
    , trade_datetime::date AS "date"
FROM
    stock_data
    INNER JOIN LATERAL (
      SELECT
        LAST_VALUE(stock_price) OVER (PARTITION BY trade_datetime::date) AS closing_price
      FROM
        stock_data AS closing_data
      WHERE closing_data.trade_datetime::date = stock_data.trade_datetime::date
    ) AS closing ON true
GROUP BY
    trade_datetime::date
ORDER BY
    trade_datetime::date ASC

收益:

| MIN | MAX | AVG                | close | date                     |
| --- | --- | ------------------ | ----- | ------------------------ |
| 5.1 | 6.2 | 5.6500000000000000 | 6.2   | 2000-01-01T00:00:00.000Z |
| 3.4 | 5.0 | 4.4000000000000000 | 4.8   | 2000-01-02T00:00:00.000Z |
| 5.9 | 7.0 | 6.4500000000000000 | 5.9   | 2000-01-03T00:00:00.000Z |

DB Fiddle