我在表中有重要的列,
当天可能存在多条记录。一天的这些记录可能将customer_approval标记为TRUE。
我们如何编写查询来获取结果集,如下所示:
还添加了一个示例:表数据
+--------+-------------------+------------+------------+
| 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 |
+--------+-------------------+------------+------------+
提前致谢。
附:抱歉可怜的表格式。
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 )
我知道这不完美,你应该考虑例外。
模型
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表格)