R
R
Roman Rakzin2017-10-31 10:45:14
PostgreSQL
Roman Rakzin, 2017-10-31 10:45:14

How to group such sql query?

I have a table with fields

-id  
-Currencies //Название -валюта1 к валюте2
-DateTime   //Дата и время запроса
-Volume     //Объём торгов на текущую дату
-Last       //Отношение валюты1 к валюте2, тобеж цена

I want to group a bunch of rows by 10 minutes and display the trading volumes, the average price for these intervals and the deviation difference from the previous request (that is, 20 minutes ago volume 5.......10 minutes ago volume 7 .... so output =2, for this type and the average price)
I made such a request
select
  c1.cur,
  generate_series
        ( now()- INTERVAL '1 day'
        , now()::timestamp
        , '10 minutes'::interval) as dd,
  MAX(c1.volume) OVER () AS Volume, 
  round( AVG(c1.last)::numeric,8) as price_m,
  MIN(c1.last) as min_price,
  MAX(c1.last) as max_price,
  round((MAX(c1.last) - MIN(c1.last))::numeric,8) AS delta_price,
  round((MAX(c1.last) / MIN(c1.last)-1)::numeric,8) AS delta_procent_price
--Вот здесь хочу ещё вывести поле цены, относительно предыдущей цены, но не получается 
  --lag(c1.last) OVER(ORDER BY datetime DESC )  as lag_last

from currencies c1 
WHERE c1.cur='BTC-XRP'

GROUP BY volume,   c1.cur 
order by volume,c1.cur

Now I have dates displayed with an interval of 10 minutes, but all other lines are all the same - If I add other fields to the grouping, then it's the same

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
V Sh., 2017-10-31
@JuniorNoobie

Now there is no time to try, but I would do this:
1) introduce an additional field for grouping / sorting by time interval (your ten minutes). Most likely something like an integer divided by seconds_from_beginning_of_day by 600 (10 minutes in seconds);
3) we group everything that is needed by this field;
3) joined exactly the same query with this very field to our table (join), but with an offset (we connect the tables by the calculated field t1.group-id = t2.group-id - 1).
4) calculated the missing things: the difference between adjacent time intervals

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question