【问题标题】:how to query for month and weekday?如何查询月份和工作日?
【发布时间】:2021-12-13 00:57:28
【问题描述】:

我有一个查询,我正在做这样的事情

 query =
  from(
    u in User,
    where: u.user_id == ^user_id,
    group_by: [
      fragment("date_part(?,?)::int", "month", u.inserted_at),
      u.user_id
    ],
    select: %{
      month: fragment("date_part(?,?)::int", "month", u.inserted_at),
      weekly: filter(count(u.user_id), fragment("date_trunc('week', ?) = date_trunc('week', current_timestamp)", u.inserted_at)),
      monthly: count(u.user_id),
    }
  )

我试图得到一个结果,我想知道每个月有多少用户插入,工作日和周末有多少用户?

结果会是这样的

[
  %{month: 10, users: 5, weekday: 2, weekend: 3},
  %{month: 9, users: 5, weekday: 1, weekend: 4}
]

在这之后我不知道如何继续,请给我一些建议

【问题讨论】:

  • 绑定t从何而来?也许你的意思是u
  • 是的,就是你。等我改一下
  • 现在可以用了吗?如果没有,请尝试在"month" 之前添加一个引脚,例如^"month",或者将其内联到片段表达式中,例如fragment("date_part('month', ?)", u.inserted_at)
  • 一个月它工作正常。我想要它在工作日和周末使用
  • 我不知道如何提取

标签: elixir ecto


【解决方案1】:

只是一些 PostgreSQL 方言中的 SQL 语句。

SELECT
  date_part('year', users.inserted_at) AS year,  -- remove this line if you think January 2020 and January 2021 are the same month.
  date_part('month', users.inserted_at) AS month,
  date_part('isodow', users.inserted_at) >= 6 AS weekend,
  COUNT(users.id) AS "count"
FROM
  users
GROUP BY
  year,  -- remove this line if you think January 2020 and January 2021 are the same month.
  month,
  weekend
ORDER BY
  year ASC,  -- remove this line if you think January 2020 and January 2021 are the same month.
  month ASC,
  weekend ASC

您无法仅通过 SQL 查询获得所需的答案,因为 usersweekend/weekday 的聚合具有不同的粒度。您必须在 RAM 中进行一些计算。

【讨论】:

  • date_part('isodow', users.inserted_at) >= 6 AS 周末,这部分不是会给我一个布尔值吗?
  • 是的,确实如此。你不能聚合不同的粒度,所以这应该是你最好的选择。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-31
  • 1970-01-01
  • 1970-01-01
  • 2019-06-04
  • 1970-01-01
  • 2012-10-19
  • 2015-11-25
相关资源
最近更新 更多