【问题标题】:Postgresql count by past weeks过去几周的 Postgresql 计数
【发布时间】:2017-02-17 14:50:10
【问题描述】:
select id, wk0_count
from teams
left join
    (select team_id, count(team_id) as wk0_count
    from (
        select created_at, team_id, trunc(EXTRACT(EPOCH FROM age(CURRENT_TIMESTAMP,created_at)) / 604800) as wk_offset
        from loan_files
        where loan_type <> 2
        order by created_at DESC) as t1
    where wk_offset = 0
    group by team_id) as t_wk0
on teams.id = t_wk0.team_id

我创建了上面的查询,显示每个团队在给定的一周内做了多少贷款。第 0 周是过去 7 天。

理想情况下,我想要一个表格,显示每个团队在过去 8 周内做了多少贷款,按周分组。输出如下所示:

关于最佳方法的任何想法?

【问题讨论】:

  • Mysql 还是 postgresql?
  • @GurV 在我看来像 Postgres

标签: postgresql aggregate


【解决方案1】:
select
    t.id,
    count(week = 0 or null) as wk0,
    count(week = 1 or null) as wk1,
    count(week = 2 or null) as wk2,
    count(week = 3 or null) as wk3
from
    teams t
    left join
    loan_files lf on lf.team_id = t.id and loan_type <> 2
    cross join lateral
    (select (current_date - created_at::date) / 7 as week) w
group by 1

在 9.4+ 版本中使用 aggregate filter syntax:

count(*) filter (where week = 0) as wk0,

lateral 来自 9.3。在以前的版本中,将 week 表达式移动到过滤条件。

【讨论】:

  • 谢谢 - 我将深入研究聚合过滤器 synatx。也许这就是我收到此错误的原因:错误:运算符不存在:日期/整数第 12 行:(选择 current_date - lf.created_at::date / 7 作为星期)... ^ 提示:没有运算符与给定名称匹配和参数类型。您可能需要添加显式类型转换。
  • @LancePoole 已修复
  • - 关于查询的快速问题。在teams 表中有没有出现在这个查询中的teams.id。这是为什么?我尝试了左连接,但这不起作用。理想情况下,结果会列出团队中的每个 teams.id。
  • @LancePoole 要使left join 工作,必须将where 条件移动到join 条件。我相应地编辑了查询。
【解决方案2】:

下面的查询怎么样?

SELECT team_id AS id, count(team_id) AS wk0_count
FROM teams LEFT JOIN loan_files ON teams.id = team_id
WHERE loan_type <> 2
  AND trunc(EXTRACT(epoch FROM age(CURRENT_TIMESTAMP, created_at)) / 604800) = 0
GROUP BY team_id

值得注意的变化是:

  • 子查询中的 ORDER BY 子句没有意义;
  • 从未使用过最里面的子查询中的created_at;
  • wk_offset 测试移到 WHERE 子句上,而不是分两个不同的步骤完成;
  • 不需要最外层的子查询。

【讨论】:

  • Fabian - 我是否会在输出中每周多次执行此查询,然后加入这些查询?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-23
相关资源
最近更新 更多