The following works:
>> r = u.utility_data.select("utility_id,
sum(ami_residential)").group("utility_id")
=> #<ActiveRecord::Relation [#<UtilityDatum id: nil, utility_id:
5621>]>
>> r.first[:sum]
=> 263
but when written as a one-liner:
>> u.utility_data.select("utility_id,
sum(ami_residential)").group("utility_id").first[:sum]
it fails with "PG::GroupingError: ERROR: column "
utility_data.id" must
appear in the GROUP BY clause or be used in an aggregate function" I
THINK what's happening is that the working version generates the
following SQL:
SELECT utility_id, sum(ami_residential)
FROM "utility_data"
WHERE "utility_data"."utility_id" = $1
GROUP BY utility_id [["utility_id", 5621]]
whereas the failing version adds "ORDER BY" and "LIMIT" to the query:
SELECT utility_id, sum(ami_residential)
FROM "utility_data"
WHERE "utility_data"."utility_id" = $1
GROUP BY utility_id
ORDER BY "utility_data"."id" ASC
LIMIT 1 [["utility_id", 5621]]
which triggers the grumpy ol' postgresql error.
So two questions:
- is this expected behavior?
- is there a way to inhibit the addition of ORDER BY and LIMIT?
Thanks...
--
Posted via
http://www.ruby-forum.com/.