首页 > 解决方案 > PostgreSQL Query GROUP BY Year/Month - 没有函数与给定名称匹配?

问题描述

我正在编写一个 PostgreSQL 查询,该查询显示按月创建的新用户注册数量,可以追溯到数据库中的开始时间。这是我所拥有的:

SELECT COUNT(id)
FROM users
WHERE users.created_at IS NOT NULL
GROUP BY YEAR(users.created_at), MONTH(users.created_at)

我的目标是获得类似于以下内容的输出:

2019 | August | 500
2019 | July | 444
2019 | June | 333

问题是我收到以下错误:

ERROR:  function year(timestamp without time zone) does not exist
LINE 4: GROUP BY YEAR(users.created_at), MONTH(users.created_at)
                 ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.
, Time: 0.079000s

我怎样才能让这个查询工作?

标签: sqlpostgresql

解决方案


在 Postgres 中,使用date_trunc()

SELECT date_trunc('month', u.created_at) as yyyymm, COUNT(*)
FROM users u
WHERE u.created_at IS NOT NULL
GROUP BY yyyymm
ORDER BY yyyymm;

推荐阅读