So the database table headers are:
Date | buyPrice | sellPrice | buyVolume | sellVolume | exchange
I'm trying to:
From what I'm reading I can use rows or was there a better solution?
(Using postgresql)
Edit: If we assume we have 3 exchanges with the following data:
|Date | buyPrice | sellPrice | buyVolume | sellVolume | exchange | |1-1-2017 | 1 | 1 | 1 | 1 | exchangeA | |1-1-2017 | 2 | 1 | 2 | 1 | exchangeB | |1-1-2017 | 3 | 1 | 3 | 1 | exchangeC |
The solution output should be
| Date | buyPrice | buyVolume | buyExchange | sellPrice | sellVolume | sellExchange | | 1-1-2017 | 1 | 1 | exchangeA | 3 | 1 | exchangeC
I tried a different approach using CTE:
WITH MinMaxPrice AS (
SELECT
createdAt, MIN(buyPrice) AS MinBuyPrice, MAX(sellPrice) AS MaxSellPrice
FROM quotes
GROUP BY createdAt
)
SELECT
MinMaxPrice.createdAt,
MinMaxPrice.MinBuyPrice,
qBuy.buyVolume,
qBuy.exchange AS buyExchange,
MinMaxPrice.MaxSellPrice,
qSell.sellVolume,
qSell.exchange AS sellExchange,
MinMaxPrice.MinBuyPrice - MinMaxPrice.MaxSellPrice AS spread
FROM MinMaxPrice
INNER JOIN quotes qBuy ON MinMaxPrice.createdAt = q.createdAt AND MinMaxPrice.MinBuyPrice = q.buyPrice
INNER JOIN quotes qSell ON MinMaxPrice.createdAt = q.createdAt AND MinMaxPrice.MaxSellPrice = q.sellPrice
;
I don't have PostgreSQL here so I couldn't test it, but I believe it works.
If you encounter any problem, let me know and I will fix it.
Ok so I managed to get it thanks to some other questions..
SELECT t1.createdAt, t1.sellPrice, t1.exchangeId AS sellExchange, t2.buyPrice, t2.exchangeId AS buyExchange, t1.sellPrice - t2.buyPrice AS spread,
CASE
WHEN t1.sellVolume < t2.buyVolume THEN t1.sellVolume
ELSE t2.buyVolume
END AS minVolume
FROM
(SELECT a.createdAt, a.sellPrice, a.sellVolume, a.exchangeid, a.quoteId
FROM quotes a
INNER JOIN (
SELECT createdAt, max(sellPrice) AS sellPrice
FROM quotes
GROUP BY createdAt
) b ON a.createdAt = b.createdAt AND a.sellPrice = b.sellPrice)
t1 INNER JOIN
(SELECT a.createdAt, a.buyPrice, a.buyvolume, a.exchangeid, a.quoteId
FROM quotes a
INNER JOIN (
SELECT createdAt, min(buyPrice) AS buyPrice
FROM quotes
GROUP BY createdAt
) b ON a.createdAt = b.createdAt AND a.buyPrice = b.buyPrice)
t2 ON t1.createdAt = t2.createdAt
Will return createdAt | sellPrice | sellExchange | buyPrice | buyExchange | volume| spread
createdAt | sellPrice | sellExchange | buyPrice | buyExchange | volume| spread
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.