如何按计数和位置组合 postgres 组

How to combine postgres group by count and where

使用 Rails 4.2 和 Postgres,我创建了以下查询,以根据每只鸟的目击次数为我提供目击 table 中鸟类 ID 的唯一列表。另请注意,我正在使用 Kaminari gem 进行分页。

 Sighting.select("bird_id, COUNT(sightings.id) as sightings_count").group(:bird_id).order('sightings_count DESC').page(1)

返回预期的 ActiveRecordRelation 效果很好。当我尝试将它与地理编码器 gems .near 方法

结合使用时,问题就出现了
Sighting.near([-31.0, 151.0], 1000, units: :km).select("bird_id, COUNT(sightings.id) as sightings_count").group(:bird_id).order('sightings_count DESC').page(1)

这会生成查询和错误

SELECT  sightings.*, 6371.0 * 2 * ASIN(SQRT(POWER(SIN((-31.0 - sightings.lat) * PI() / 180 / 2), 2) + COS(-31.0 * PI() / 180) * COS(sightings.lat * PI() / 180) * POWER(SIN((151.0 - sightings.lng) * PI() / 180 / 2), 2))) AS distance, MOD(CAST((ATAN2( ((sightings.lng - 151.0) / 57.2957795), ((sightings.lat - -31.0) / 57.2957795)) * 57.2957795) + 360 AS decimal), 360) AS bearing, bird_id, COUNT(sightings.id) as sightings_count FROM "sightings" WHERE (sightings.lat BETWEEN -39.993216059187304 AND -22.006783940812696 AND sightings.lng BETWEEN 140.50821379697885 AND 161.49178620302115 AND (6371.0 * 2 * ASIN(SQRT(POWER(SIN((-31.0 - sightings.lat) * PI() / 180 / 2), 2) + COS(-31.0 * PI() / 180) * COS(sightings.lat * PI() / 180) * POWER(SIN((151.0 - sightings.lng) * PI() / 180 / 2), 2)))) BETWEEN 0.0 AND 1000) GROUP BY bird_id  ORDER BY distance ASC, sightings_count DESC LIMIT 25 OFFSET 0

PG::GroupingError: ERROR: 列 "sightings.id" 必须出现在 GROUP BY 子句中或在聚合函数中使用

通过鸟类计数不正确将 id 添加到组中,据我了解 select 中的 COUNT 是一个聚合函数,其中确实包括 sightings.id.

我怎样才能成功地将两者结合起来?

注意:我确实尝试了以下方法,但是这个 returns 是哈希而不是 AR 关系。

Sighting.near([@lat, @lng], @range, units: :km, order:nil).group(:bird_id).order('count_id DESC').page(@page).count(:id)

感谢您的帮助!!

创建自定义近范围是最简单的解决方法,因为我没有使用添加到每条记录的方位角或距离属性,因此整个 select sql 由 near I 生成不需要。而不是 select(options[:select]) 我用我想要的 select 替换了它。

scope :birds_by_sighting, lambda{ |location, *args|
latitude, longitude = Geocoder::Calculations.extract_coordinates(location)
if Geocoder::Calculations.coordinates_present?(latitude, longitude)
  options = near_scope_options(latitude, longitude, *args)
  select("bird_id, COUNT(sightings.id) as sightings_count").group(:bird_id).where(options[:conditions]).order('sightings_count DESC')
else
  # If no lat/lon given we don't want any results, but we still
  # need distance and bearing columns so you can add, for example:
  # .order("distance")
  select(select_clause(nil, null_value, null_value)).where(false_condition)
end
}