group_by 中的 Ecto Fragment 插值变量

Ecto Fragment interpolating var in group_by

我正在尝试以下操作:

query =
  from s in State,
    group_by:
      fragment("date_part(?, ?)", ^group, s.timestamp_start),
    select:
      {fragment("date_part(?, ?)", ^group, s.timestamp_start), count(s.id)}
Repo.all(query)

其中 group 可能是 ['minute''hour''day'] 之一。

但是,我收到以下错误:

ERROR 42803 (grouping_error) column "s0.timestamp_start" must appear in the GROUP BY clause or be used in an aggregate function

但是如果我将 s.timestamp_start 添加到 group_by 子句,我不会得到预期的结果,因为日期是按 timestamp_start 分组的,而不是按定义的部分分组的。

如何在不必为每个 group 可能性指定查询(在 fragment 内传递文字值)的情况下执行此操作?

进行分组时,select 的所有内容都必须与分组依据相关,或者使用聚合函数之一。由于您按年、月等分组,数据库不知道在该行中显示哪个 timestamp_start。如果您想显示该特定行的所有时间戳,您可以使用一个片段来构建最终会成为 string_agg(s.timestamp_start, ',')

的片段

找到答案

您可以在片段中使用as来互相引用:

    from(m in Message,,
      group_by: fragment("timestamp"),
      select: fragment("date_trunc(?, ?) as timestamp", ^timeseries, m.inserted_at)
    )