简体   繁体   English

Postgres-按多列分组,Rails

[英]Postgres - Group by multiple columns, Rails

I have a table named property_audit_version_histories. 我有一个名为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 结果包含3条记录,其中2条具有相同的操作和user_id现在我需要使用列操作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 基于线程PG :: GroupingError:错误:列“ events.id”必须出现在GROUP BY子句中或在聚合函数中使用我已经修改了如下代码

@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. 现在错误消失了,但结果仍然有3条记录。 After grouping i expect only 2 records. 分组后,我希望只有2条记录。 在此处输入图片说明

Any idea on how to fix this? 关于如何解决此问题的任何想法?

You cant select all columns like mysql in postgresql when doing aggregrates. 进行聚集时,您无法在postgresql中选择所有类似mysql的列。

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 但是对于您知道的列,将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. 确保100%确保分组后这些列的值相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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