简体   繁体   中英

Postgres - Group by multiple columns, Rails

I have a table named property_audit_version_histories. i am fetching the records using the following code

@version_logs = PropertyAuditVersionHistory
                    .includes(:property_audit_version, :user)
                    .where(property_audit_version_id: params[:id])

The result contain 3 records, 2 of which have the same action and user_id Now i need to group the records using the columns action, user_id

I am getting the following error when i try to group the records

@version_logs = PropertyAuditVersionHistory
                        .includes(:property_audit_version, :user)
                        .where(property_audit_version_id: params[:id])
                        .group("action, user_id")

PG::GroupingError: ERROR:  column "property_audit_version_histories.id" must appear in the GROUP BY clause or be used in an aggregate function

Based on the thread PG::GroupingError: ERROR: column "events.id" must appear in the GROUP BY clause or be used in an aggregate function i have modified the code as follows

@version_logs = PropertyAuditVersionHistory
                    .includes(:property_audit_version, :user)
                    .group("property_audit_version_histories.id")
                    .where(property_audit_version_id: params[:id])
                    .group("action, user_id")

Now the error is gone but still the result is having 3 records. After grouping i expect only 2 records. 在此处输入图片说明

Any idea on how to fix this?

You cant select all columns like mysql in postgresql when doing aggregrates.

So I guess this should work.

@version_logs = PropertyAuditVersionHistory    
                    .where(property_audit_version_id: params[:id])
                    .group("action", "user_id", "property_audit_version_id")
                    .select("user_id", "action", "property_audit_version_id")

I dont know how is your model but this should work. If you need more fields let me know

What you need to do is specify which columns you want with

  .select("user_id")

But for the columns you know will be the same use max(columnName) as columnName

for example:

.select("MAX(user_id) as user_id, action")

Make sure you are 100% sure that those columns will be the same value after grouping.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM