Postgresql计数过去几周

时间:2017-02-17 14:50:10

标签: postgresql aggregate

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周内所做的贷款数量,按周分组。输出看起来像:

enter image description here

有关最佳方法的任何想法吗?

2 个答案:

答案 0 :(得分:0)

以下查询怎么样?

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子句上移动,而不是在两个不同的步骤中完成;
  • 不需要最外面的子查询。

答案 1 :(得分:0)

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表达式移动到过滤条件。