sql - postgres - SELECT/GROUP BY 中的部分列 - 列必须出现在 GROUP BY 子句中或用于聚合函数

标签 sql mysql ruby-on-rails postgresql heroku

以下两个语句都会在 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);

错误是:

column "cdrs.start_time" must appear in the GROUP BY clause or be used in an aggregate function

我对 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)。有什么建议吗?

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

最佳答案

您做了问题中未描述的其他事情,因为您的两个查询都运行良好。在 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)

关于sql - postgres - SELECT/GROUP BY 中的部分列 - 列必须出现在 GROUP BY 子句中或用于聚合函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1780893/

相关文章:

sql - mysql二进制比较不使用索引

jquery - 如何在 Rails 应用程序中启动和停止 javascript 发起的查询?

sql - 带有 select 返回一个值的 PostgreSQL 函数

c# - 如何在数据库中 nvarchar() 列的不同行中更新列表框的多个选择?

查询表并从查询结果重建字符串的 Mysql 函数

php - 如何在多选表单上回显数据库中多选的选定值

mysql - php登录系统警告

mysql - 创建一个表,其名称必须是另一个表中的主键

ruby-on-rails - Elastic Beanstalk 数据库池问题

javascript - 如何在 Rails View 中使用 AJAX