sql - 在时间戳上使用 date_trunc 时为 "column must appear in the GROUP BY clause"

标签 sql postgresql

我有一个 SQL 查询,它计算具有给定创建日期的联系人。创建日期以毫秒为单位存储为 unix 时间戳,我正在使用 to_timestamp 方法正确格式化它:

SELECT count(*) AS "Count", date_trunc('month', to_timestamp("contacts"."createdate"::double precision / 1000)) AS "Create Date"
FROM "contacts"
GROUP BY "contacts"."createdate"
ORDER BY "contacts"."createdate" ASC

结果如下:

Count | Create Date
-----------------------------------------
1     | Sunday, February 1, 2015 12:00 AM
1     | Sunday, February 1, 2015 12:00 AM
1     | Wednesday, April 1, 2015 12:00 AM
1     | Wednesday, April 1, 2015 12:00 AM
1     | Wednesday, April 1, 2015 12:00 AM

我想按月对它们进行分组,因此对于上面的示例,我希望:

Count | Create Date
-----------------------------------------
2     | February 2015
3     | April 2015

我将 SQL 更改为以下内容:

SELECT count(*) AS "Count", date_trunc('month', to_timestamp("contacts"."createdate"::double precision / 1000)) AS "Create Date"
FROM "contacts"
GROUP BY date_trunc('month', to_timestamp("contacts"."createdate"::double precision / 1000))
ORDER BY "contacts"."createdate" ASC

但是收到一个错误:

ERROR: column "contacts.createdate" must appear in the GROUP BY clause or be used in an aggregate function

有什么办法可以正确地做到这一点?

最佳答案

您可以通过编号引用 SELECT 中的元素:

SELECT count(*) AS "Count", date_trunc('month', to_timestamp("contacts"."createdate"::double precision / 1000)) AS "Create Date"
FROM "contacts"
GROUP BY date_trunc('month', to_timestamp("contacts"."createdate"::double precision / 1000))
ORDER BY 2 ASC

关于sql - 在时间戳上使用 date_trunc 时为 "column must appear in the GROUP BY clause",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48171880/

相关文章:

ruby-on-rails - 使用 Rails Active Record 的 IN 列表中的 Postgres ORDER BY 值

postgresql - 如何在 Windows 上的 postgresql 9.1 中安装 pgcrypto?

android - 如何按 ORDER 构造 SQLite 查询到 GROUP?

php - MYSQL JOIN所有子行,父行只显示一次

postgresql - Postgres : how do you round a timestamp up or down to the nearest minute?

java - PostgreSql 中的事务

php - 将点插入启用 PostGis 的 Postgres 数据库

mysql - 当他们使用 php 登录时,尝试对每个帐户进行唯一查询

sql - 插入使用值

mysql - mysql查询的左连接还是联合?