这是查询
WITH dates AS (
SELECT current_date - serie AS date
FROM generate_series(0, 365, 1) AS serie
), items AS (
SELECT *
FROM items
WHERE created_at BETWEEN now() - interval '6 months' AND now()
)
SELECT dates.date, count(items)
FROM dates
LEFT OUTER JOIN items ON items.created_at::date = dates.date
GROUP BY dates.date
除了一件事之外,一切正常 - 我需要以某种方式连续几天替换now()
。
因此,对于每一天,根据当天的条件计算项目计数。
只是无法引用它。
有没有解决方案?
答案 0 :(得分:0)
WITH dates AS (
SELECT current_date - serie AS date
FROM generate_series(0, 365, 1) AS serie
)
SELECT dates.date, count(items)
FROM dates
LEFT OUTER JOIN items ON created_at BETWEEN dates.date- interval '6 months' AND dates.date
GROUP BY dates.date;
答案 1 :(得分:0)
我找到了以下解决方案,其效果与Vao Tsun提出的相同:
WITH dates AS (
SELECT current_date - serie AS date
FROM generate_series(0, 365, 1) AS serie
), date_intervals AS (
SELECT
(dates.date - INTERVAL '6 months') AS start_date,
dates.date AS end_date
FROM dates
)
SELECT date_intervals.end_date, count(items)
FROM date_intervals
LEFT OUTER JOIN items ON items.created_at BETWEEN date_intervals.start_date AND date_intervals.end_date
GROUP BY 1
ORDER BY 1