且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

GroupingError:错误:列""必须出现在 GROUP BY 子句中或在聚合函数中使用

更新时间:2023-09-17 07:53:16

你不能在 Postgres 中将 SELECT *GROUP BY some_column 结合起来(除非 some_columncode> 是 PK),因为这是一个矛盾.所有非聚合列(在聚合函数之外的 SELECTHAVINGORDER BY 子句中使用)必须在 GROUPBY 列表 - 其中主键列可以替换表的所有列.否则未定义哪个值从聚合集合中选择.

Per documentation:

根据文档:>

当存在 GROUP BY 或任何聚合函数时,它对引用未分组的 SELECT 列表表达式无效列,聚合函数内或未分组的列除外在功能上依赖于分组列,因为会有否则对于未分组的返回值可能不止一个柱子.如果分组列(或其子集)是包含表的主键未分组的列.

When GROUP BY is present, or any aggregate functions are present, it is not valid for the SELECT list expressions to refer to ungrouped columns except within aggregate functions or when the ungrouped column is functionally dependent on the grouped columns, since there would otherwise be more than one possible value to return for an ungrouped column. A functional dependency exists if the grouped columns (or a subset thereof) are the primary key of the table containing the ungrouped column.

已知某些其他 RDBMS 在这里玩弄肮脏的把戏,并允许这样做并选择任意值......

您似乎想要一个已发表评论的独特患者列表,每个患者都有最新条评论.Postgres 中最简单的方法是使用 DISTINCT ON:

You seem to want a list of unique patients that have commented, with the latest comment each. The simplest way in Postgres is with DISTINCT ON:

SELECT DISTINCT ON (patient_id) *
FROM   comments
WHERE  clinician_id = $1
ORDER  BY patient_id, created_at DESC NULLS LAST;

但这不会与 SQLite 一起使用 - 它不应该在循环中开始:

But this won't fly with SQLite - which should not be in the loop to begin with:

NULLS LAST 仅在 created_at 可以为 NULL 时才相关:

NULLS LAST is only relevant if created_at can be NULL:

DISTINCT ON 的详细信息: