我正在尝试根据日期将查询结果存储到月表中(最近30天)。
2018年2月1日的例子: 给了我一个 310
的数量SELECT *
FROM properties p
INNER JOIN orders o
ON o.property_id = p.id
WHERE o.type = 'Order::PromotedListing'
AND o.expired_at::DATE > '2018-02-01'
AND o.created_at::DATE <= '2018-02-01'
ORDER BY o.updated_at
对于 2018年2月2日: 给了我一个 307 的计数
SELECT *
FROM properties p
INNER JOIN orders o
ON o.property_id = p.id
WHERE o.type = 'Order::PromotedListing'
AND o.expired_at::DATE > '2018-02-02'
AND o.created_at::DATE <= '2018-02-02'
ORDER BY o.updated_at
等等。
我想根据临时表/ CTE中的日期存储过去30天的次数。像这样的东西 -
day, count
2018-02-01, 310
2018-02-02, 307
...
...
所以我提出了这个问题,但它没有做我想做的事情。
WITH monthly_dates AS (
SELECT d.date as day
FROM generate_series(current_date - interval '30 day',
current_date,
'1 day') AS d
),
featured_listings AS (
SELECT o.expired_at::date, o.created_at::date, o.updated_at::date
FROM properties p
INNER JOIN orders o
ON o.property_id = p.id
WHERE o.type = 'Order::PromotedListing'
)
SELECT m.day, COUNT(*)
FROM monthly_dates AS m
LEFT JOIN featured_listings AS f
ON m.day = f.updated_at
WHERE f.expired_at > m.day
AND f.created_at <= m.day
GROUP BY 1
ORDER BY 1;
任何有关完成此任务的输入都将受到赞赏。
答案 0 :(得分:1)
你似乎想要:
SELECT g.dte, count(o.property_id)
FROM generate_series('2018-02-01'::date, '2018-02-28'::date, interval '1 day'
) g(dte) INNER JOIN
orders o
ON o.expired_at::DATE > g.dte AND o.created_at::DATE <= o.gte
GROUP BY g.dte
ORDER BY g.dte;
我认为您不需要此查询的properties
表。