2017-07-31 57 views
1

我試圖在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月,也是在前幾年。

+0

請你詳細說明數據樣本後和預期的結果 –

回答

0

使用date_trunc(..)功能:

SELECT pt.created_at::date, pt.customer_id, c.name, 
    sum(pt.amount/100::double precision) filter (where date_trunc('month', pt.created_at) = date_trunc('month', NOW() - interval '1 month')) 
from 
    product_transactions pt 
LEFT JOIN customers c 
    ON c.id= pt.customer_id 
GROUP BY pt.created_at::date 
+0

應該不是當年被過濾爲好,因爲我想2017年,而不是佔所有條目在六月昔年? – OAK

+0

'date_trunc('month',..)''會返回像'2017-07-01 00:00:00'這樣的值 – Nick

+0

所以它會保存關於年和月的知識,但拋出其他任何東西。這正是你所需要的AFAICS。 – Nick