sql - 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
我怎样才能让这个查询工作?
解决方案
在 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;
推荐阅读
- python - Airflow Unittest.cfg 权限问题?
- salesforce - 如何使用 Salesforce 在案例类型中实施完整搜索?
- c++ - 分离 header.h、main.cpp 和 implementation.cpp 中的代码
- django - 找不到 Apache2 Ubuntu 服务器模块 'django'
- flutter - Flutter:如何删除复选框(多个 CheckboxListTile)的额外填充?
- python - 在Python中获取回归模型的贝塔系数
- r - 使用 R,如何使用 dplyr 的超前和滞后函数正确地从 POSIXct 变量中减去一秒?
- php - HttpOpenRequest () Wininet c++ e PHP
- javascript - 使用firestore登录时如何在本机反应中使用实时数据库?
- python - 调用类时局部变量引用错误