我有一个工作数据库,过去一个月我想按周数。我当前的查询已执行,但是按日历周而不是我想要的跟踪周进行分块:
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天?
答案 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;