如何按周分组而不进行分块(查询_trailing_ 4周)

时间:2018-06-20 13:49:00

标签: sql postgresql datetime group-by

我有一个工作数据库,过去一个月我想按周数。我当前的查询已执行,但是按日历周而不是我想要的跟踪周进行分块:

SELECT date_trunc('week', scheduled_for::date) AS weekly,
   COUNT(*)           
FROM jobs_job WHERE state = 'complete' AND scheduled_for > NOW() - INTERVAL '1 month' 
GROUP BY weekly
ORDER BY weekly;

如何更改此设置,以使每个“每周”周期恰好是7天?

2 个答案:

答案 0 :(得分:1)

您可能想使用extract week

SELECT EXTRACT(isoyear FROM scheduled_for) as yearly,
       EXTRACT(WEEK FROM scheduled_for) as weekly,
       COUNT (*)
FROM jobs_job WHERE state = 'complete' AND scheduled_for > NOW() - INTERVAL '1 month' 
GROUP BY EXTRACT(isoyear FROM scheduled_for),
         EXTRACT(WEEK FROM scheduled_for)
ORDER BY EXTRACT(isoyear FROM scheduled_for),
         EXTRACT(WEEK FROM scheduled_for);

答案 1 :(得分:1)

我认为您希望日期差异以天为单位,然后除以7以定义星期。那应该是:

SELECT scheduled_for::date + floor((current_date - scheduled_for::date) / 7) * interval '1 week' AS weekly,
       COUNT(*)           
FROM jobs_job WHERE state = 'complete' AND scheduled_for > NOW() - INTERVAL '1 month' 
GROUP BY weekly
ORDER BY weekly;