mysql - 将mysql查询转换为postgres时出错
问题描述
以下查询适用于 MySQL:
SELECT
f.created_date as time_sec
,sum(f.value) as value
, date_format( f.created_date , '%a') as metric
FROM ck_view_fills as f
GROUP BY date_format(f.created_date, '%a' )
我已将我的数据库迁移到 PostgreSQL,现在我正在将我的查询转换为匹配。我的天真转换如下所示:
SELECT
f.created_date as time_sec
,sum(f.value) as value
, to_char( f.created_date , "D") as metric
FROM ck_view_fills as f
GROUP BY to_char( f.created_date , "D")
不接受此查询,PostgreSQL 产生的错误消息如下:
查询错误 (7):错误:列“f.created_date”必须出现在 GROUP BY 子句中或用于聚合函数第 2 行:f.created_date as time_sec
据我所知, f.created_date 确实在 group by 子句中使用。我也看到了使用这种语法的例子。那么这个错误的原因是什么,我该如何解决呢?
解决方案
Postgres 是正确的。事实上,使用最新版本的 MySQL 时,您的查询也会失败——使用默认设置。
只需使用聚合函数:
SELECT MIN(f.created_date) as time_sec,
SUM(f.value) as value
TO_CHAR(f.created_date, 'D') as metric
FROM ck_view_fills f
GROUP BY to_char(f.created_date , 'D');
您应该在 MySQL 中使用过类似的构造(关于MIN()
-- 或MAX()
)。
推荐阅读
- python - 如何在gyame中同时移动一个班级的多个实例
- python - 从 yahoo.finance 中提取数据
- python - 用python渲染jpg字节数组序列
- ios - APNS 将通知修改为静默通知
- java - 如何处理和自定义来自 Spring Boot ldap 的错误 401?
- nginx - Nginx 重定向
- kubernetes - Kubernetes 编辑秘密错误:“无法从...恢复切片”
- javascript - 为谷歌图表设置倾斜文本(材料条形图)
- python - Django 模型与原始 SQL 查询
- javascript - 页面加载时,Zurb Foundation .sticky 粘到底部会在页面顶部闪烁