gpt4 book ai didi

postgresql - 选择按日期排序的唯一记录

转载 作者:行者123 更新时间:2023-11-29 12:22:06 26 4
gpt4 key购买 nike

我有以下 2 个模型:

class Schedule < ActiveRecord::Base    
attr_accessible :description, :deadline_on, :repeat
has_many :scheduled_transactions
end

class ScheduledTransaction < ActiveRecord::Base
attr_accessible :transaction_on, :description
belongs_to :schedule
end

我想从每个时间表中找到最后安排的交易。我知道我能做到:

Schedule.all.each do |schedule|
schedule.scheduled_transactions.order(:transaction_on).last
end

但我想优化它并选择单个数据库。

我尝试构建 Rails 查询:

ScheduledTransaction.select('DISTINCT(schedule_id), scheduled_transactions.*').order('transaction_on DESC')

翻译成:

SELECT DISTINCT(schedule_id), scheduled_transactions.* FROM "scheduled_transactions" ORDER BY transaction_on DESC

但它并没有给出预期的结果。有多行具有相同的 schedule_id。

我的目标是选择包含每个计划的最后计划交易的计划交易列表。有什么建议吗?

(PostgreSQL) 9.1.9

最佳答案

正如 Guedes 所写,您可以为此使用 DISTINCT ON:

SELECT DISTINCT ON (schedule_id) *
FROM scheduled_transactions
ORDER BY schedule_id, transaction_on DESC

关于postgresql - 选择按日期排序的唯一记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16100488/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com