问题
Maybe, this question is a little stupid, but I'm confused.
How to group records by specified column ? :)
Item.group(:category_id)
does't works...
It says:
ActiveRecord::StatementInvalid: PGError: ERROR: column "items.id" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: SELECT "items".* FROM "items" GROUP BY category_id
What kind of aggregate function should i use?
Please, could you provide a simple example.
回答1:
You will have to define, how to group values that share the same category_id
. Concatenate them? Calculate a sum?
To create comma-separated lists of values your statement could look like this:
SELECT category_id
,string_agg(col1, ', ') AS col1_list
,string_agg(col2, ', ') AS col2_list
FROM items
GROUP BY category_id
You need Postgres 9.0 or later for string_agg(col1, ', ').
In older versions you can substitute with array_to_string(array_agg(col1), ', ')
. More aggregate functions here.
To aggregate values in PostgreSQL is the clearly superior approach as opposed to aggregating values in the client. Postgres is very fast at this and it reduces (network) traffic.
回答2:
You can use sum
, avg
, count
or any other aggregate function. More on this topic you can find here.
But it seems that you don't really need to use SQL grouping.
Try to fetch all records and then use Array#collect function to group Item
s by category_id
回答3:
Grouping in SQL means that the server groups one or more records from the database table into one resulting row. So, if you for example group by category_id
, you might have several records matching the given category, so you can't expect the database to return all columns from the table (that's what SELECT *
actually does).
Instead, when you use GROUP BY
, you can SELECT
only:
- columns you have grouped by, and/or
- aggregate functions which are performed on all the records belonging to a resulting group
Depending on what you exactly need, modify your .select
accordingly.
来源:https://stackoverflow.com/questions/8575740/group-by-specified-column-in-postgresql