1
我有一個包含createddate的記錄表。我想返回過去6個日曆月中的每個月的新記錄,包括本月的部分月份。我很瞭解SQL Server,但不熟悉PostgreSQL。在PostgreSQL中查找過去n個月中的每個月的新記錄
我已經能夠與此查詢以獲取滾動個月的數據:從5/22-6/21
select
COUNT(ID) as Total,
COUNT(CASE WHEN createddate between (now() - '1 month'::interval)::timestamp AND now() THEN AG.ID END) as ThisMonth,
COUNT(CASE WHEN createddate between (now() - '2 month'::interval)::timestamp AND (now() - '1 month'::interval)::timestamp THEN AG.ID END) as LastMonth,
COUNT(CASE WHEN createddate between (now() - '3 month'::interval)::timestamp AND (now() - '2 month'::interval)::timestamp THEN AG.ID END) as PrevMonth,
COUNT(CASE WHEN createddate between (now() - '4 month'::interval)::timestamp AND (now() - '3 month'::interval)::timestamp THEN AG.ID END) as PrevMonth2,
COUNT(CASE WHEN createddate between (now() - '5 month'::interval)::timestamp AND (now() - '4 month'::interval)::timestamp THEN AG.ID END) as PrevMonth3,
COUNT(CASE WHEN createddate between (now() - '6 month'::interval)::timestamp AND (now() - '5 month'::interval)::timestamp THEN AG.ID END) as PrevMonth4
FROM a_group AG
但在6/21,這將返回數據,4/22-5/21等
我想要的數據如下:6/1-6/21(部分本月),5/1-5/31等。
有什麼建議嗎?我也懷疑我可以在循環中做到這一點,但對語法還不夠熟悉。目前,我正在從PostgreSQL Maestro對備份文件進行測試。
謝謝。
你釘它,湯姆。這正是我需要的。 – nycdan
我很想把它放到控制循環中,這樣我就可以更容易地修改週期數。如果有人願意獲得積分...... :) – nycdan
您可以使用窗口函數來獲得所需的結果(請參閱http://www.postgresql.org/docs/current/static/tutorial-window.html )。例如:SELECT DISTINCT date_trunc('month',createddate)as start,count()OVER(PARTITION BY date_trunc('month',createddate))FROM a_group; – Tom