这就是我正在尝试做的事情:
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/