找到最小值+最大值和关联列

时间:2017-08-26 01:56:20

标签: sql postgresql greatest-n-per-group

所以数据库表头是:

Date | buyPrice | sellPrice | buyVolume | sellVolume | exchange

我试图:

  1. 列表项
  2. 按日期分组
  3. 对于每个组,找到最低买入价和与之相关的交易所
  4. 查找最大sellPrice及与之关联的交易所
  5. 找出max(sellPrice) - min(buyPrice)
  6. 之间的差异

    从我正在阅读的内容中我可以使用行还是有更好的解决方案?

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

2 个答案:

答案 0 :(得分: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所以我无法测试它,但我相信它有效。

如果您遇到任何问题,请告诉我,我会解决。

答案 1 :(得分:0)

好的,所以我设法通过其他一些问题得到了它。

createdAt | sellPrice | sellExchange | buyPrice | buyExchange | volume| spread

会回来 ArrayList<ArrayList<String>> arrayListContainer = new ArrayList<>(); ArrayList<String> temporaryArrayList = new ArrayList<>(); temporaryArrayList.add("I"); temporaryArrayList.add("you"); temporaryArrayList.add("he"); temporaryArrayList.add("she"); temporaryArrayList.add("we"); arrayListContainer.add(temporaryArrayList); temporaryArrayList.clear(); temporaryArrayList.add("Rahim"); temporaryArrayList.add("jon"); temporaryArrayList.add("don"); temporaryArrayList.add("shaila"); arrayListContainer.add(temporaryArrayList); temporaryArrayList.clear(); System.out.println(arrayListContainer.size());