我有这个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?
答案 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