Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save javier/a4965c4c878dfd2ff99ec5237f2d5ed7 to your computer and use it in GitHub Desktop.
Save javier/a4965c4c878dfd2ff99ec5237f2d5ed7 to your computer and use it in GitHub Desktop.
QuestDB SQL Window Functions Example
SELECT * FROM trades;
SELECT timestamp, symbol, price * amount AS volume,
FROM trades;
SELECT timestamp, symbol, price * amount AS volume,
sum(price * amount) OVER (ORDER BY timestamp) AS total_volume
FROM trades;
SELECT timestamp, symbol, side, price * amount AS volume,
SUM(price * amount) OVER (PARTITION BY symbol ORDER BY timestamp) AS total_volume
FROM trades;
SELECT timestamp, symbol, side, price * amount AS volume,
SUM(price * amount) OVER (
PARTITION BY symbol, side
ORDER BY timestamp
) AS total_volume
FROM trades;
SELECT timestamp, symbol, side, price * amount AS volume,
SUM(price * amount) OVER (
PARTITION BY symbol, side
ORDER BY timestamp
) AS total_volume
FROM trades
WHERE symbol = 'ETH-USD' AND side='buy';
SELECT timestamp, symbol, side, price * amount AS volume,
SUM(price * amount) OVER (
PARTITION BY symbol, side
ORDER BY timestamp
RANGE 1 second PRECEDING
) AS total_volume
FROM trades
WHERE symbol = 'ETH-USD' AND side='buy';
SELECT timestamp, symbol, side, price * amount AS volume,
SUM(1) OVER (
PARTITION BY symbol, side
ORDER BY timestamp
RANGE 1 second PRECEDING
) AS total_volume
FROM trades
WHERE symbol = 'ETH-USD' AND side='buy';
SELECT timestamp, symbol, side, price * amount AS volume,
SUM(1) OVER (
PARTITION BY symbol, side
ORDER BY timestamp
ROWS 10 PRECEDING
) AS total_volume
FROM trades
WHERE symbol = 'ETH-USD' AND side='buy';
SELECT timestamp, symbol, side, price * amount AS volume,
AVG(price) OVER (
PARTITION BY symbol, side
ORDER BY timestamp
ROWS 10 PRECEDING
) AS total_volume
FROM trades
WHERE symbol = 'ETH-USD' AND side='buy';
SELECT timestamp time, symbol, price as priceBtc
, avg(price) over (PARTITION BY symbol ORDER BY timestamp RANGE between 10 seconds PRECEDING AND CURRENT ROW) movingAvg10Sec
, avg(price) over (PARTITION BY symbol ORDER BY timestamp RANGE between 30 seconds PRECEDING AND CURRENT ROW) movingAvg30Sec
, avg(price) over (PARTITION BY symbol ORDER BY timestamp RANGE between 45 seconds PRECEDING AND CURRENT ROW) movingAvg45Sec
FROM trades WHERE dateadd('m', -5, now()) < timestamp AND symbol = 'BTC-USD'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment