postgresql使用having max子句获取两列的唯一组合

yx2lnoni  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(425)

我正在使用postgresql。我有一个货币换算表,它有以下列dateofclosing,fromcurrency,tocurrency,closingrate。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

我尝试使用groupby with having max子句,但由于varchar到date的转换而出错。有人能给我一个更好的解决办法吗?

e0uiprwp

e0uiprwp1#

我们可以用 DISTINCT ON 在这里:

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

演示

33qvvth1

33qvvth12#

使用 distinct on :

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

相关问题