Search code examples
sqlpostgresqlgreatest-n-per-group

Find the min + max value and associated column


So the database table headers are:

Date | buyPrice | sellPrice | buyVolume | sellVolume | exchange

I'm trying to:

  1. List item
  2. Group by date
  3. For each group, find the minimum buy price and the exchange associated to it
  4. Find the maximum sellPrice and the exchange associated with it
  5. Find the diff between max(sellPrice) - min(buyPrice)

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


Solution

  • 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