如何在Postresql中执行查询,返回按月分组创建的数据计数?

时间:2017-06-04 01:14:35

标签: sql postgresql

在postgresql中,如何执行一个返回按月创建的特定表的行总和的查询?我希望结果如下:

month: January
count: 67

month: February
count: 85
....
....

假设我有一张桌子users。此表包含主键idcreated_at列,其中时间以ISO8601格式存储。去年创建了n个用户,现在我想知道有多少是按月创建的,我希望以上述格式返回给我的数据 - 按月分组,相关计数反映了多少用户是在那个月创建的。

有谁知道如何在postgresql中执行上述SQL查询?

1 个答案:

答案 0 :(得分:1)

查询看起来像这样:

select date_trunc('month', created_at) as mm, count(*)
from users u
where subscribed = true and
      created_at >= '2016-01-01' and
      created_at < '2017-01-01'
group by date_trunc('month', created_at);

我不知道常数'2017-03-20 13:38:46.688-04'的来源。

当然,您可以使年度比较动态:

select date_trunc('month', created_at) as mm, count(*)
from users u
where subscribed = true and
      created_at >= date_trunc('year', now()) - interval '1 year' and
      created_at < date_trunc('year', now())
group by date_trunc('month', created_at);