我试图在PostgreSQL中使用内置的filter
函数来过滤日期范围,以仅汇总此时间范围内的条目。 我不明白为什么过滤器没有被应用。 我正在尝试筛选上一个月的日期为created_at
的所有产品交易(因此在本例中是2017年6月创建的)。PostgreSQL - 日期过滤功能
SELECT pt.created_at::date, pt.customer_id,
sum(pt.amount/100::double precision) filter (where (date_part('month', pt.created_at) =date_part('month', NOW() - interval '1 month') and
date_part('year', pt.created_at) = date_part('year', NOW())))
from
product_transactions pt
LEFT JOIN customers c
ON c.id= pt.customer_id
GROUP BY pt.created_at::date,pt.customer_id
请找我的预期结果(每天前一个月量的总和 - 因为如果存在这一天的条目中的每个CUSTOMER_ID)我从查询得到与实际结果 - 在(使用date_trunc
)。 预期结果:
created_at| customer_id | amount
2017-06-30 1 220.5
2017-06-28 15 34.8
2017-06-28 12 157
2017-06-28 48 105.6
2017-06-27 332 425.8
2017-06-25 1 58.0
2017-06-25 23 22.5
2017-06-21 14 88.9
2017-06-17 2 34.8
2017-06-12 87 250
2017-06-05 48 135.2
2017-06-05 12 95.7
2017-06-01 44 120
结果:
created_at| customer_id | amount
2017-06-30 1 220.5
2017-06-28 15 34.8
2017-06-28 12 157
2017-06-28 48 105.6
2017-06-27 332 425.8
2017-06-25 1 58.0
2017-06-25 23 22.5
2017-06-21 14 88.9
2017-06-17 2 34.8
2017-06-12 87 250
2017-06-05 48 135.2
2017-06-05 12 95.7
2017-06-01 44 120
2017-05-30 XX YYY
2017-05-25 XX YYY
2017-05-15 XX YYY
2017-04-30 XX YYY
2017-03-02 XX YYY
2016-11-02 XX YYY
实际结果给我的总和为数据库中的所有日期,所以没有日期的时间框架在查询中被应用的一个原因我不能理解。我看到的日期既不是在2017年6月,也是在前几年。
请你详细说明数据样本后和预期的结果 –