postgresql 从表中获取最近三个月的记录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3117582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
get last three month records from table
提问by ungalnanban
How to get last 3 months records from the table.
如何从表中获取最近 3 个月的记录。
SELECT * from table where month > CURRENT_DATE-120 and month < CURRENT_DATE order by month;
SELECT * from table where month > CURRENT_DATE-120 and month < CURRENT_DATE 按月排序;
I have used the above query is it correct? shall I use this for get last 3 month record from the table.
我用过上面的查询是否正确?我应该用它从表中获取最近 3 个月的记录吗?
回答by dzida
You can use built-in INTERVAL
instruction
您可以使用内置INTERVAL
指令
Check how this works:
检查这是如何工作的:
SELECT CURRENT_DATE - INTERVAL '3 months'
and you can rewrite your SQL to:
您可以将 SQL 重写为:
SELECT * from table where date > CURRENT_DATE - INTERVAL '3 months'
(not checked but this should give you an idea how to use INTERVAL instruction)
(未选中,但这应该让您了解如何使用 INTERVAL 指令)
回答by analogue
Try that:
试试看:
SELECT *
FROM table
WHERE month BETWEEN EXTRACT(MONTH FROM NOW() - INTERVAL '3 months')
AND EXTRACT(MONTH FROM NOW())
ORDER BY month
;