MySQL到PostgreSQL:如何修改这个SQL查询?

时间:2010-12-20 20:37:25

标签: sql mysql postgresql refactoring

我有这个MySQL查询,它使用MONTH()YEAR()

SELECT 
  MONTH(created_at) AS month, 
  YEAR(created_at) AS year 
FROM users 
GROUP BY MONTH(created_at), YEAR(created_at) 
ORDER BY YEAR(created_at), MONTH(created_at)

如何修改该查询以使用PostgreSQL?

2 个答案:

答案 0 :(得分:4)

SELECT 
  extract(MONTH from created_at) AS month, 
  extract(YEAR from created_at) AS year 
FROM users 
GROUP BY extract(MONTH from created_at), extract(YEAR from created_at) 
ORDER BY extract(MONTH from created_at), extract(YEAR from created_at) 

这是最新的手册
http://www.postgresql.org/docs/current/static/functions-datetime.html#FUNCTIONS-DATETIME-EXTRACT

顺便说一下:这也是适用于MySQL的标准(ANSI)SQL。

答案 1 :(得分:2)

http://www.postgresql.org/docs/9.0/static/functions-datetime.html

SELECT 
  EXTRACT(MONTH FROM created_at) AS month, 
  EXTRACT(YEAR FROM created_at) AS year 
FROM users 
GROUP BY EXTRACT(MONTH FROM created_at), EXTRACT(YEAR FROM created_at)
ORDER BY EXTRACT(YEAR FROM created_at), EXTRACT(MONTH FROM created_at)

此语法应适用于PostgreSQL,Oracle和Teradata