将mysql转换为postgresql

时间:2014-02-10 11:42:56

标签: mysql postgresql

我有一个工作的mysql查询,但我无法使用postgres。这是查询(我已将日期格式更改为to_char

SELECT country as grouper, date(users.created_at) as date, 
       to_char(users.created_at, '%Y-%m') as date_group, 
       count(id) as total_count 
  FROM "users" 
 WHERE (users.created_at >= '2011-12-01') 
   AND (users.created_at <= '2014-02-11') 
 GROUP BY grouper, date_group 
 ORDER BY date ASC

我收到错误:

PG::Error: ERROR:  column "users.created_at" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: SELECT country as grouper, date(users.created_at) as date, t...

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

SELECT country as grouper, date(MIN(users.created_at)) as date, 
       to_char(MIN(users.created_at), '%Y-%m') as date_group, 
       count(id) as total_count 
  FROM "users" 
HAVING (users.created_at >= '2011-12-01') 
   AND (users.created_at <= '2014-02-11') 
 GROUP BY grouper, date_group 
 ORDER BY date ASC

MySQL不是很严格。在标准符合SQL中,所有列值必须在非分组字段上使用聚合函数(SUM,COUNT,MAX,MIN) - 使用GROUP BY时。

老实说,我不完全确定GROUP BY中的data_group;可以丢弃吗? 另请注意,我已将WHERE切换为HAVING。

答案 1 :(得分:1)

您应该使用GROUP BY部分中的每个选定列。

SELECT country as grouper, to_char(created_at, '%Y-%u') as date_group, count(id) as total_count
FROM "users" 
WHERE created_at >= '2013-10-01' 
AND created_at <= '2014-02-11' 
GROUP BY grouper, date_group 
ORDER BY date_group ASC