使用Rails进行PostgreSQL分组错误

时间:2013-11-10 18:00:09

标签: sql ruby-on-rails postgresql grouping

我有以下查询:

SELECT
EXTRACT (
    HOUR
    FROM
        interventions.created_at :: TIMESTAMP
) AS DATE,
COUNT (interventions. ID) AS total
FROM
    "interventions"
INNER JOIN medical_records ON (
    (
        medical_records.medical_recordable_type = 'Intervention'
    )
    AND (
        medical_records.medical_recordable_id = interventions. ID
    )
)
INNER JOIN patients ON (
    patients. ID = medical_records.patient_id
)
WHERE
    (
         interventions.created_at BETWEEN '2011-11-10 00:00:00'
         AND '2014-11-10 00:00:00'
    )
AND (
    medical_records.hospitalization = FALSE
)
AND (
    patients.birth_date BETWEEN '1892-12-31 23:50:39'
    AND '2013-12-31 22:59:59'
)
GROUP BY
    DATE
ORDER BY
    interventions. ID DESC,
    DATE ASC

我收到以下错误:

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

以下是我的代码的相关部分:

query = query.select("EXTRACT(HOUR FROM interventions.created_at::timestamp) AS date, COUNT(interventions.id) AS total")
query = query.group("EXTRACT(HOUR FROM interventions.created_at::timestamp)")
query = query.order("EXTRACT(HOUR FROM interventions.created_at::timestamp) ASC")

我不明白,因为“interventions.id”列在select中的COUNT()函数中使用。

有关如何解决此问题的任何想法?

谢谢。

1 个答案:

答案 0 :(得分:1)

从ORDER BY子句中删除interventions_id。