Rails:group和count sql查询包括零

时间:2013-10-15 15:23:38

标签: sql ruby-on-rails postgresql

我能够运行此查询以生成区域的哈希并逐个分组(包括零计数):

Region.includes(:answers).group("regions.region").count("answers")

产生

{"blar"=>0, "East"=>0, "East Midlands"=>11, "London"=>8, "North East"=>0, "North West"=>0, "Northern Ireland"=>0, "Rest of World"=>89, "Scotland"=>0, "South East"=>0, "South West"=>0, "Wales"=>0, "West Midlands"=>0, "Yorkshire and the Humber"=>0}

但是,当我想要一个特定问题的结果(包括计数零)时,它只会显示带答案的区域的哈希值。

查询:

Region.includes(:answers).where("answers.question_id = 14").group("regions.region").count("answers")

产生

{"East Midlands"=>3, "London"=>1, "Rest of World"=>4}

我理解查询将仅选择question_id的答案,因此这给出了给定的输出,但我尝试了许多不同的查询(包括LEFT OUT JOINS)并且无法获得所需的结果。

供参考:

地区has_many:答案

回答belongs_to:region

回答belongs_to:问题

由于

2 个答案:

答案 0 :(得分:1)

对于任何感兴趣的人,我能够通过将sql IS NULL OR添加到where子句来解决这个问题:

Region.includes(:answers).where("answers.id IS NULL OR answers.question_id = 14").group("regions.region").count("answers")

产:

{"blar"=>0, "East"=>0, "East Midlands"=>1, "London"=>0, "North East"=>0, "North West"=>0, "Northern Ireland"=>0, "Rest of World"=>4, "Scotland"=>0, "South East"=>0, "South West"=>0, "Wales"=>0, "West Midlands"=>0, "Yorkshire and the Humber"=>0} 

可能不是最好的方式,但它完成了工作

答案 1 :(得分:0)

使用显式NULL添加SELECT,如下所示:

Region.outer_joins(:answers).select('region.name IS NULL').