我可以从下面的代码创建postgresql视图吗?是否有必要?,因为现在加载需要几秒钟,但将来我将不得不在其上添加日期范围。如果是,请有人帮我写下来。
report = self.project_reports
results_total = report.where('value < ?', 50).group("key_id").select('key_id')
fifty = report.where('value BETWEEN ? AND ?', 41, 50).group("key_id").select('key_id')
forty = report.where('value BETWEEN ? AND ?', 31, 40).group("key_id").select('key_id')
thirty = report.where('value BETWEEN ? AND ?', 21, 30).group("key_id").select('key_id')
twenty = report.where('value BETWEEN ? AND ?', 11, 20).group("key_id").select('key_id')
ten = report.where('value BETWEEN ? AND ?', 4, 10).group("key_id").select('key_id')
three = report.where('value = ?', 3).group("key_id").select('key_id')
two = report.where('value = ?', 2).group("key_id").select('key_id')
one = report.where('value = ?', 1).group("key_id").select('key_id')
pos = {fif: fifty.count.size, four: forty.count.size, thir: thirty.count.size, twen: twenty.count.size, te: ten.count.size, thr: three.count.size, tw: two.count.size, on: one.count.size, result_t: total}
答案 0 :(得分:1)
这在SQL意义上不是一个真正的“视图”(你只能通过DDL查询创建它),但你当然可以构建一个ActiveRelation(这可能就是你的意思)。请注意,您正在任意切换“值”和“位置”,这是故意的吗?我在这里使用“价值”来保持一致性:
group_sql = <<-SQL
CASE WHEN value = 1 THEN 'one'
WHEN value = 2 THEN 'two'
WHEN value = 3 THEN 'three'
WHEN value <= 10 THEN 'ten'
WHEN value <= 20 THEN 'twenty'
WHEN value <= 30 THEN 'thirty'
WHEN value <= 40 THEN 'forty'
WHEN value <= 50 THEN 'fifty'
SQL
report = self.project_reports.where('value < 50').group(group_sql)
positions = report.count
positions['total'] = positions.values.sum