复杂Rails Active Record查询选择具有真实结果的记录,以便当天最新更新其他创建的记录

问题描述 投票:0回答:2

我在表中有重要的列,

  • customer_approval(boolean)
  • created_at(datetime)
  • updated_at(datetime)

当天可能存在多条记录。一天的这些记录可能将customer_approval标记为TRUE。

我们如何编写查询来获取结果集,如下所示:

  1. 即使当天有多个记录,也每天只选择一条记录
  2. 必须首先选择记录,以记录customer_approval为true的位置
  3. 如果记录不符合上述条件,请选择当天根据created_at或updated_at列创建或更新的最新条目
  4. 创建时,根据日期范围(从日期 - 到日期)选择所有记录。

还添加了一个示例:表数据

+--------+-------------------+------------+------------+
| row_id | customer_approval | created_at | updated_at |
+--------+-------------------+------------+------------+
|      1 | TRUE              | 2017-12-01 | 2017-12-01 |
|      2 | FALSE             | 2017-12-01 | 2017-12-01 |
|      3 | NIL               | 2017-12-01 | 2017-12-01 |
|      4 | NIL               | 2017-12-02 | 2017-12-02 |
|      5 | FALSE             | 2017-12-03 | 2017-12-03 |
|      6 | NIL               | 2017-12-03 | 2017-12-03 |
|      7 | NIL               | 2017-12-04 | 2017-12-05 |
+--------+-------------------+------------+------------+

2017-12-01和2017-12-05日期范围的预期结果集:

+--------+-------------------+------------+------------+
| row_id | customer_approval | created_at | updated_at |
+--------+-------------------+------------+------------+
|      1 | TRUE              | 2017-12-01 | 2017-12-01 |
|      4 | NIL               | 2017-12-02 | 2017-12-02 |
|      6 | NIL               | 2017-12-03 | 2017-12-03 |
|      7 | NIL               | 2017-12-04 | 2017-12-05 |
+--------+-------------------+------------+------------+

提前致谢。

附:抱歉可怜的表格式。

sql ruby-on-rails postgresql activerecord
2个回答
0
投票

Postgresql查询

SELECT DISTINCT ON (created_at) row_id, customer_approval, created_at
FROM the_table
ORDER BY customer_approval DESC, created_at DESC;

在铁轨中

TheTable.select("DISTINCT ON (created_at) row_id, customer_approval, created_at")
        .order(customer_approval: :desc, created_at: :desc )

0
投票

我知道这不完美,你应该考虑例外。

模型

class Customer < ApplicationRecord

  scope :approval, -> { where customer_approval: true }
  scope :waiting, -> { where customer_approval: nil }

  scope :for_day, ->(date) {
    where(
      arel_table[:created_at].eq(date)
      .or(arel_table[:updated_at].eq(date))
    )
  }

  def self.last_change
    order(created_at: :desc, updated_at: :desc).first
  end
end

调节器

def fetch_customers(first, last)
  result = []

  first.upto(last) do |date|
    customer = Customer.for_day(date).approval.first
    customer ? (result << customer) : (result << Customer.for_day(date).waiting.last_change)
  end

  result
end

# first = Date.parse('2017-12-01')
# last = Date.parse('2017-12-05')
# fetch_customer(first, last)

附:希望你的rails版本4+(适用于Arel表格)

© www.soinside.com 2019 - 2024. All rights reserved.