我試圖在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月,也是在前幾年。
請你詳細說明數據樣本後和預期的結果 –