【问题标题】:PostGreSql Get Unique combination of two columns using Having Max ClausePostGreSql 使用拥有 Max 子句获取两列的唯一组合
【发布时间】:2020-10-16 18:50:19
【问题描述】:

我正在使用 postGreSql。我有一个货币换算表,其中包含以下列 DateOfClosing、fromCurrency、toCurrency、closureRate。 dateOfClosing 是 varchar 格式 我想找到过去 5 天中 fromCurrency 和 toCurrency 的最新独特组合 例如,如果表格内容如下

DateOfClosing    fromCurrency     toCurrency   closingRate
2020-06-25       INR              USD          1
2020-06-26       INR              USD          3
2020-06-26       JPY              USD          2
2020-06-24       THB              USD          1

它应该返回:

DateOfClosing    fromCurrency     toCurrency   cloisingRate
2020-06-26        INR             USD          3
2020-06-26        JPY             USD          2
2020-06-24        THB             USD          1

我尝试使用带有 max 子句的 groupby,但由于 varchar 到日期的转换而出错。谁能给我一个更好的解决方案?

【问题讨论】:

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


    【解决方案1】:

    使用distinct on:

    select distinct on (fromCurrency, toCurrenty) t.*
    from mytable t
    where dateOfClosing >= current_date - interval '5 day'
    order by fromCurrency, toCurrenty, dateOfClosing desc
    

    【讨论】:

      【解决方案2】:

      我们可以在这里使用DISTINCT ON

      SELECT DISTINCT ON (fromCurrency, toCurrency) *
      FROM yourTable
      ORDER BY fromCurrency, toCurrency, DateOfClosing DESC;
      

      Demo

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-22
        • 1970-01-01
        • 2015-09-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多