0

以下两个语句都会在 Postgres 中产生错误:

SELECT substring(start_time,1,8) AS date, count(*) as total from cdrs group by date;
SELECT substring(start_time,1,8) AS date, count(*) as total from cdrs group by substring(start_time,1,8);

错误是:

列“cdrs.start_time”必须出现在 GROUP BY 子句中或在聚合函数中使用

我对 postgres 文档的阅读是 SELECT 和 GROUP BY 都可以使用表达式 postgres 8.3 SELECT

start_time 字段是一个字符串,具有 ccyymmddHHMMSS 形式的日期/时间。在 mySQL 中,它们都产生期望和预期的结果:

+----------+-------+
| date     | total |
+----------+-------+
| 20091028 |     9 |
| 20091029 |   110 |
| 20091120 |    14 |
| 20091121 |     4 |
+----------+-------+
4 rows in set (0.00 sec)

我需要坚持使用 Postgres (heroku)。有什么建议么?

ps 还有很多其他的讨论,讨论 GROUP BY 中缺少的项目,以及为什么 mySQL 接受这个,为什么其他人不接受......严格遵守 SQL 规范等,但我认为这与1062158/converting-有很大不同mysql-select-to-postgresql1769361/postgresql-group-by-different-from-mysql保证一个单独的问题。

4

3 回答 3

4

您做了其他未在问题中描述的事情,因为您的两个查询都可以正常工作。在 8.5 和 8.3.8 上测试:

# create table cdrs (start_time text);
CREATE TABLE

# insert into cdrs (start_time) values ('20090101121212'),('20090101131313'),('20090510040603');
INSERT 0 3

# SELECT substring(start_time,1,8) AS date, count(*) as total from cdrs group by date;
   date   | total
----------+-------
 20090510 |     1
 20090101 |     2
(2 rows)

# SELECT substring(start_time,1,8) AS date, count(*) as total from cdrs group by substring(start_time,1,8);
   date   | total
----------+-------
 20090510 |     1
 20090101 |     2
(2 rows)
于 2009-11-23T08:53:39.380 回答
1

总结一下,错误

列“cdrs.start_time”必须出现在 GROUP BY 子句中或在聚合函数中使用

是由ORDER BY start_time子句引起的(在这种情况下)。完整的声明需要是:

SELECT substring(start_time,1,8) AS date, count(*) as total FROM cdrs GROUP BY substring(start_time,1,8) ORDER BY substring(start_time,1,8);

或者

    SELECT substring(start_time,1,8) AS date, count(*) as total FROM cdrs GROUP BY date ORDER BY date;
于 2009-11-24T19:26:16.763 回答
0

您可以尝试两件简单的事情:

  1. 升级到 postgres 8.4.1
    两个查询在 pg841 下对我来说都很好(tm)

  2. 按序号位置分组
    也就是说,GROUP BY 1在这种情况下。

于 2009-11-23T05:43:21.120 回答