0

我需要计算选择查询中的用户数。这是我的 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),

我需要在查询中使用schemayear变量,但续集说我

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 块?

4

1 回答 1

0

我发现我不需要使用 block it 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

改进此代码的想法正在接受...)

于 2018-11-09T03:15:38.953 回答