PostgreSQL:随时间推移的行计数

PostgreSQL:随时间推移的行计数,postgresql,postgresql-9.4,Postgresql,Postgresql 9.4,我有一个简单的mySQL sql脚本,它会随时间向我输出特定表的行数(基于表中的datetime字段) 现在我想将其迁移到PostgreSQL,但不知道如何将变量迁移到基于pg的语法 当然,内部声明是没有问题的: SELECT TO_CHAR(t.created,'YYYY-MM') AS label , COUNT(t.id) AS cnt FROM templates t GROUP BY label

我有一个简单的mySQL sql脚本,它会随时间向我输出特定表的行数(基于表中的datetime字段)

现在我想将其迁移到PostgreSQL,但不知道如何将变量迁移到基于pg的语法

当然,内部声明是没有问题的:

SELECT TO_CHAR(t.created,'YYYY-MM') AS label
              , COUNT(t.id) AS cnt
           FROM templates t
          GROUP BY label
          ORDER BY label
这里有谁能帮我做可变部分

下面是一个包含数据的简单表格:

create TABLE "templates" (
    "id" bigserial,
    "title" varchar(2048) default NULL::character varying,
    "created" timestamp,
    PRIMARY KEY ("id")
);

insert into templates(title, created) values('test', '2011-03-01');
insert into templates(title, created) values('test 2', '2011-03-02');
insert into templates(title, created) values('test 3', '2011-03-03');
insert into templates(title, created) values('test 4', '2011-03-04');
insert into templates(title, created) values('test 5', '2011-03-05');
insert into templates(title, created) values('test 6', '2011-04-01');
insert into templates(title, created) values('test 7', '2011-04-02');
insert into templates(title, created) values('test 8', '2011-04-03');
insert into templates(title, created) values('test 9', '2011-04-04');
insert into templates(title, created) values('test 10', '2011-04-05');
… // 300 more for 2011-05
此查询的示例输出(基于带有“已创建”列的记录)为:

M-11-03:5 M-11-04:510(5+5) M-11-05:300310(5+5+300)
(这是的衍生产品)

对于日期格式化,您可以使用
M-YY-MM
作为格式化字符串来获取例如:
M-11-03
。 并通过以下方式使用加积门
计数

这项工作:

select month, hm, sum(hm) over(order by month)
from(
select to_char(created, 'M-YYYY-MM') as month, count(*) as hm
from templates
group by 1
) x
order by month

您可能需要一些窗口功能。但如果您需要帮助,请通过添加somme数据更新您的问题,以及您真正期望的结果。thx@Houari!为了更容易识别目标,我添加了示例输出。@wingedparter done!不需要将日期转换为字符。您可以选择并聚合
date\u trunc('mon',created)
@a\u horse\u和\u no\u name查看此结果,而不使用
distinct
非常好的代码!但我不知道如何将第二列(滚动总数)纳入其中。我是否需要在(按日期排序的字段)上使用sum(count_字段)进行联接? M-11-03: 5 5 M-11-04: 5 10 (5 + 5) M-11-05: 300 310 (5 + 5 + 300)
SELECT distinct TO_CHAR(created,'M-YY-MM'), 
       COUNT(id) OVER ( ORDER BY TO_CHAR(created,'YY-MM')) 
FROM templates 
ORDER BY 1
select month, hm, sum(hm) over(order by month)
from(
select to_char(created, 'M-YYYY-MM') as month, count(*) as hm
from templates
group by 1
) x
order by month