2017-08-26 66 views
1

因此數據庫表格的標題是:按日期 找到最小+最大值和相關的列

  1. 列表項
  2. 組:

    Date | buyPrice | sellPrice | buyVolume | sellVolume | exchange

    我想

  3. 對於每個組,找到最低購買價格和與之相關聯的交易所
  4. Fin d最大sellPrice與它
  5. 關聯的Exchange查找最大(sellPrice)之間的差異 - 分鐘(buyPrice)

從我正在讀我可以用行或有沒有一個更好的解決辦法?

(使用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

+0

在你的輸出例子,你怎麼弄''的3' sellPrice'如果你有您的數據示例中只有'1'作爲'sellPrice'? – MiguelKVidal

回答

0

行,所以我設法得到它歸功於一些其他問題..

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

0

我嘗試了一種使用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在這裏,所以我無法測試它,但我相信它的工作原理。

如果您遇到任何問題,請告訴我,我會解決它。

+0

上面的信息只是在一張表中。然而BuyPrice和SellPrice總是不同的交易所(即對於給定的日期,exchange1有最低的買入價格,而exchange2有最高的賣出價格) –

+0

剛剛在上面增加了一些信息 –

相關問題