[英]Find the min + max value and associated column
因此,数据库表头是:
Date | buyPrice | sellPrice | buyVolume | sellVolume | exchange
我试图:
从我正在阅读的内容中,我可以使用行,还是有更好的解决方案?
(使用postgresql)
编辑:如果我们假设与以下数据进行3次交换:
|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 |
解决方案输出应为
| Date | buyPrice | buyVolume | buyExchange | sellPrice | sellVolume | sellExchange | | 1-1-2017 | 1 | 1 | exchangeA | 3 | 1 | exchangeC
我使用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
;
我这里没有PostgreSQL,所以无法测试它,但我相信它可以工作。
如果您遇到任何问题,请告诉我们,我们会解决。
好的,由于其他一些问题,我设法做到了。
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
将返回createdAt | sellPrice | sellExchange | buyPrice | buyExchange | volume| spread
createdAt | sellPrice | sellExchange | buyPrice | buyExchange | volume| spread
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.