【问题标题】:How to use multiple distinct on statements in Postgres while retaining the correct order如何在 Postgres 中使用多个 distinct on 语句,同时保持正确的顺序
【发布时间】:2020-11-27 09:44:20
【问题描述】:

我有一张 Postgres 中的天气预报表格,看起来像这样

在这里,每 15 分钟同时发布一次风力和太阳预报。我希望使用distinct on() 语句从该表中选择最新的风能和太阳能预测。但是,当我仅在time 列上使用它时,它会删除风预报,因为该预报在太阳能预报前一分钟被丢弃。我曾尝试使用distinct on(time, forecast),但后来订单以某种方式搞砸了,我不再使用最新的dump_date(见下文)

如何在多个列上使用distinct on() 语句同时仍保留顺序?我现在使用的查询是

select
    distinct on ("time", "forecast") *
from table
order by "time"

让这个查询保持动态很重要,所以硬编码dump_date 对我来说不是一个选择。

【问题讨论】:

  • 请不要添加图片。它使复制测试数据变得异常复杂。请添加一些示例数据和预期输出作为可复制文本。

标签: postgresql sql-order-by distinct-on


【解决方案1】:

我会将dump_date DESC 添加到ORDER

SELECT DISTINCT ON (time, forecast)
    *
FROM t
ORDER BY time, forecast, dump_date DESC

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-31
    • 2019-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    相关资源
    最近更新 更多