我需要计算选择查询中的用户数。这是我的 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 上的实现,它有效
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>
或者如果我直接将年份 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(...)
在这种情况下,有什么方法可以将变量传递给 select 块?