我有一个带有DATE字段的表(也是类型)。如何编写查询以获取像这样的月份间隔:
start end
2015-01-01 2015-01-31
2015-02-01 2015-02-28
2015-03-01 2015-03-31
and so on ..
我将使用什么样的SQL函数来获得此结果? 我使用的是Postgres DB。
查询创建了一个存储数据的表:
CREATE TABLE "DEPOSIT_EVENT" (
id bigint NOT NULL,
amount numeric(19,2),
date timestamp without time zone,
description character varying(255),
eventtype character varying(255),
processingdate timestamp without time zone,
status boolean,
view boolean,
deposit_id bigint,
CONSTRAINT "DEPOSIT_EVENT_pkey" PRIMARY KEY (id ),
CONSTRAINT fk_dp0pc33hchopclsau0uknefgr FOREIGN KEY (deposit_id)
REFERENCES "DEPOSITS" (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
);
我想按月间隔拍摄,如上所述。
例如,我有几行:
id amount date
1 100 2014-01-01 08:39:51.774
2 31 2014-01-10 08:39:51.774
3 2 2014-01-21 08:39:51.774
4 22 2014-02-04 08:39:51.774
5 74 2014-03-14 08:39:51.774
从中我只想要包含一个或多个这样的项目的月份期间:
column
2014-01-01 - 2014-01-30
2014-02-01 - 2014-02-28
2014-03-01 - 2014-03-31
答案 0 :(得分:0)
以下内容应该有效:
SELECT
date_trunc('MONTH', date) as start_date,
date_trunc('MONTH', date) + INTERVAL '1 MONTH - 1 day' as end_Date,
COUNT(id) AS recordcount
FROM DEPOSIT_EVENT
GROUP BY 1,2
这将获得每个日期的月份开始和月末,然后对这两个日期进行GROUP BY
。我在第三个字段recordcount
中添加了,以表明您还可以在同一查询中获得该时间段内的记录数。