postgresql - Ecto union_all 与 count(*) 查询

标签 postgresql elixir ecto

这就是我正在尝试做的事情:

thirty_days_ago_completed_visits =
  from(v in Visit,
    select: %{a: count("*")},
    where: v.papa_id == ^papa.id,
    where:
      v.scheduled_for >= ^thirty_days_ago and
        v.state in ["completed", "reviewed"]
  )

sixty_days_ago_completed_visits =
  from(v in Visit,
    select: %{b: count("*")},
    where: v.papa_id == ^papa.id,
    where:
      v.scheduled_for >= ^sixty_days_ago and
        v.state in ["completed", "reviewed"]
  )

future_scheduled_visits =
  from(v in Visit,
    select: %{c: count("*")},
    where: v.papa_id == ^papa.id,
    where: v.recurring == false,
    where: v.scheduled_for >= ^Timex.now()
  )

future_recurring_visits =
  from(v in Visit,
    select: %{d: count("*")},
    where: v.papa_id == ^papa.id,
    where: v.recurring == true,
    where: v.scheduled_for >= ^Timex.now()
  )

from(
  a in subquery(thirty_days_ago_completed_visits),
  union_all: ^sixty_days_ago_completed_visits,
  union_all: ^future_scheduled_visits,
  union_all: ^future_recurring_visits
)
|> Repo.all()
|> IO.inspect()

我收到此错误:

** (Ecto.QueryError) 子查询/cte 必须选择源 (t)、字段 (t.field) 或映射,在查询中得到:count("*"):

from v0 in PapaPal.Visit,
  where: v0.papa_id == ^"419b3f7f-b74a-42fa-a377-2b7f54886c06",
  where: v0.scheduled_for >= ^#DateTime<2020-04-18 19:31:36.774112Z> and v0.state in ["completed", "reviewed"],
  select: count("*")

我最终想要得到的是四个整数,每个查询一个整数 - 通过对数据库使用单个 SQL 查询

有什么建议吗?

最佳答案

Ecto.Query.API.count/1 的文档以及错误消息本身,清楚地表明您在将 "*" 传递给它时必须选择源、字段或映射。下面的内容可以工作。

from v0 in PapaPal.Visit,
  where: v0.papa_id == ^papa_id,
  where: v0.scheduled_for >= ^dt,
  where: v0.state in ^states,
  select: count(v0.id) # THIS

关于postgresql - Ecto union_all 与 count(*) 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61877631/

相关文章:

Elixir Ecto 自定义主键

database - Postgresql 存储过程/函数在 Multi-Tenancy 环境中的性能,该环境具有一个数据库和多个模式(每个租户一个)

mysql - SQL索引优化WHERE查询

elixir - 如何限制监护人和 Phoenix 的特定操作的权限

concurrency - 组合 Task.async_stream 与 Continuation 传递

postgresql - 使用 SSL 和 Elixir 后端连接到 Azure 上托管的 PostgreSQL

postgresql - 为 PostgreSQL 用户设置密码不起作用

SQL查找具有相邻数字的行

elixir - 列表中的 Ecto multi build_assoc

sql - Ecto - 表 B 或 C 的表 A 的外键约束,但不是 B 和 C