-1

我面临的真正战术问题是所有类别都设置为“默认”,因此如果我设置 options[:category] ​​= 'default' 它只会添加没有类别的点。因此,如果我将点添加到类别“arin”,它将不计入“默认”总数。因此,如果不是 NULL 或按类别,我尝试获取所有表,但它一直为“arin”获取相同的数量。

默认值:20

阿林:20

如果未提供类别或“默认”,则应为 40,如果参数类别为“arin”,则应为 20。

有人可以帮助我理解正确 SQL 背后的概念以获得我正在寻找的结果吗?

Rails 和 SQL 的新手。

  def self.top_scored(options = {})
   options[:table_name] ||= :users
   options[:since_date] ||= 4.months.ago
   options[:end_date] ||=  1.month.from_now
   options[:category] ||=  nil
   options[:limit]      ||= 10

  alias_id_column = "#{options[:table_name].to_s.singularize}_id"
  if options[:table_name] == :sashes
    sash_id_column = "#{options[:table_name]}.id"
  else
    sash_id_column = "#{options[:table_name]}.sash_id"
  end

  # MeritableModel - Sash -< Scores -< ScorePoints
  sql_query = <<SQL
SELECT
  #{options[:table_name]}.id AS #{alias_id_column},
  SUM(num_points) as sum_points
FROM #{options[:table_name]}
  LEFT JOIN merit_scores ON merit_scores.sash_id = #{sash_id_column}
  LEFT JOIN merit_score_points ON merit_score_points.score_id = merit_scores.id
WHERE merit_score_points.created_at > '#{options[:since_date]}' AND merit_score_points.created_at < '#{options[:end_date]}' AND (merit_scores.category IS NOT NULL OR merit_scores.category = '#{options[:category]}')
GROUP BY #{options[:table_name]}.id, merit_scores.sash_id
ORDER BY sum_points DESC
LIMIT #{options[:limit]}
SQL

  results = ActiveRecord::Base.connection.execute(sql_query)
  results.map do |h|
    h.keep_if { |k, v| (k == alias_id_column) || (k == 'sum_points') }
  end
  results
end
  end
4

1 回答 1

0

似乎没有人回答,只有投反对票。这是给未来对此提出质疑的任何人。我发现您可以拆分 sql 语句并在 SQL 周围的 rails 中使用 if 语句。

  sql_query = "SELECT
                #{options[:table_name]}.id AS #{alias_id_column},
                SUM(num_points) as sum_points
              FROM #{options[:table_name]}
                LEFT JOIN merit_scores ON merit_scores.sash_id = #{sash_id_column}
                LEFT JOIN merit_score_points ON merit_score_points.score_id = merit_scores.id
              WHERE merit_score_points.created_at > '#{options[:since_date]}' AND merit_score_points.created_at < '#{options[:end_date]}' "

  if(options[:category] != nil)
    sql_query += "AND merit_scores.category = \"#{options[:category]}\" "
  end

  sql_query += "GROUP BY #{options[:table_name]}.id, merit_scores.sash_id
                ORDER BY sum_points DESC
                LIMIT #{options[:limit]} "

  results = ActiveRecord::Base.connection.execute(sql_query)
于 2014-05-28T00:32:10.813 回答