我需要计算选择查询中的用户数。 这是我的SQL代码段
SELECT count(id) FROM demo.users WHERE year_id = 'c4c62a9d-801f-4573-92a8-aa0a8589200a'
我在
内部使用它 CASE count(DISTINCT assigned_lessons.id)
WHEN 0 THEN 0
ELSE count(DISTINCT homework_results.id) :: float /
(
count(DISTINCT assigned_lessons.id) *
(SELECT count(id) FROM demo.users WHERE year_id = 'c4c62a9d-801f-4573-92a8-aa0a8589200a')
)
END AS completed_homework_rate
这是我在续集上的有效实现
Sequel.case({ 0 => 0 },
Sequel.cast(count(:homework_results__id).distinct, :float) /
(
count(:assigned_lessons__id).distinct *
DB['demo__users'.to_sym].select do
count(id)
end.where(year_id: 'c4c62a9d-801f-4573-92a8-aa0a8589200a')
),
count(:assigned_lessons__id).distinct,
).as(:completed_homework_rate),
但是我需要使用类似的东西
Sequel.case({ 0 => 0 },
Sequel.cast(count(:homework_results__id).distinct, :float) /
(
count(:assigned_lessons__id).distinct *
DB["#{schema}__users".to_sym].select do
count(id)
end.where(year_id: year.id)
),
count(:assigned_lessons__id).distinct,
).as(:completed_homework_rate),
我需要在查询中使用schema
和year
杂音,但续集说我
undefined method `id' for #<Sequel::SQL::Identifier @value=>:year>
或者如果我直接将Year id作为字符串传递,则会以错误的方式替换schema
变量
SELECT count("id") FROM "#<Sequel::SQL::Identifier:0x00007f8d36b553b8>"."users"
简化的用例
DB[:curriculum_strands].select do
[
Sequel.case({ 0 => 0 },
Sequel.cast(count(:homework_results__id).distinct, :float) /
(
count(:assigned_lessons__id).distinct *
DB["#{schema}__users".to_sym].select do
count(id)
end.where(year_id: year.id)
),
count(:assigned_lessons__id).distinct,
).as(:completed_homework_rate),
]
end.left_join(...)
在这种情况下,有什么方法可以将变量传递给选择块?
答案 0 :(得分:0)
我发现我不需要使用select
对其进行阻止。
这是我的解决方法
DB[:curriculum_strands].select(
completed_homework_rate.as(:completed_homework_rate),
).left_join(...)
private
def completed_homework_rate
Sequel.case({ 0 => 0 },
count_distinct(:homework_results__id).cast(Float) /
(count_distinct(:assigned_lessons__id) * users_count),
count_distinct(:assigned_lessons__id),
)
end
def users_count
DB["#{schema}__users".to_sym].select { count(id) }.where(year_id: year.id)
end
def count_distinct(column)
Sequel.function(:count, column).distinct
end
改进此代码的想法正在接受...)