gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 14:33:39 25 4
gpt4 key购买 nike

我有一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com