gpt4 book ai didi

sql - PostgreSQL : column must appear in the GROUP BY clause or be used in an aggregate function

转载 作者:行者123 更新时间:2023-12-05 02:02:04 25 4
gpt4 key购买 nike

(Postgres)

我不清楚以下内容:我正在从 STUDY_T 中选择各种字段,这些字段可能是具有聚合函数的子选择。我正在检索的一个独立字段是 LOOKUP_T 连接 lookupStudyType.description,它与任何聚合函数都不相关。但是我得到了错误

ERROR:  column "lookupstudytype.description" must appear in the GROUP BY clause or be used in an aggregate function
LINE 3: lookupStudyType.description AS studyTypeDescription,...

为什么我不仅需要按 s.id 分组,还需要按 lookupStudyType.description 分组(而其他 s. 分组是不需要)?

        SELECT 
s.id AS id,
lookupStudyType.description AS studyTypeDescription,
s.name AS name,
s.abbreviation AS abbreviation,
s.start_date AS startDate,
s.end_date AS endDate,
(SELECT COUNT(r.id)
FILTER
(WHERE r.status_id IN (76, 77) )) AS recallCount,
(SELECT COUNT(DISTINCT sp.id)) AS participantCount,
(SELECT MAX(r.created_date)
FILTER
(WHERE r.status_id IN (76,77) )) AS lastRecall,
s.login_access_required AS loginAccessRequired,
s.description AS description,
s.custom_participant_exit_message AS customParticipantExitMessage
FROM study_t s
INNER JOIN lookup_t lookupStudyType
ON s.study_type_id = lookupStudyType.id
INNER JOIN study_staff_t ss
ON s.id = ss.study_id
INNER JOIN users_t u
ON ss.researcher_id = u.id
LEFT JOIN study_participants_t sp
ON s.id = sp.study_id
LEFT JOIN recalls_t r
ON r.user_id = sp.user_id
WHERE u.user_name = 'test@test.com'
GROUP BY
s.id
ORDER BY s.abbreviation ASC

最佳答案

作为一般规则,GROUP BY 子句中未列出的任何列都应在 SELECT 列表中显示聚合

例如 s.name 应该显示为 max(s.name)min(s.name) 因为它不存在在 GROUP BY 列表中。但是,PostgreSQL 为 GROUP BY 子句实现了函数依赖(一个 SQL 标准特性),并检测到 s.name 依赖于 s.id 列(大概就是PK);简而言之,每个 s.id 都有一个可能的值 s.name。因此,在 PostgreSQL 中不需要聚合此列(您可以,但不需要)。

另一方面,对于 lookupStudyType.description,PostgreSQL 无法确定它是否在功能上依赖于 s.id。您需要将其聚合为 max(lookupStudyType.description)min(lookupStudyType.description) 或任何其他聚合表达式。

附带说明一下,我很少看到在其他数据库中实现函数依赖。 PostgreSQL 不是很棒吗? (我不以任何方式隶属于 PostgreSQL)。

关于sql - PostgreSQL : column must appear in the GROUP BY clause or be used in an aggregate function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66065987/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com