SQL 查询最近5年
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9196924/
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
Querying last 5 years
提问by Evgeni Reznik
I want to query all products sold in the last 5 years.
It is possible to do it like this:
我想查询过去5年销售的所有产品。
可以这样做:
select * from products
where time between sysdate-1826 and sysdate
But it there also a nicer way instead of calculating all the days and subtract it from sysdate
?
但它还有一个更好的方法,而不是计算所有天数并从sysdate
?
回答by Justin Cave
SELECT *
FROM products
WHERE date_column >= add_months( sysdate, -12*5 )
or
或者
SELECT *
FROM products
WHERE date_column >= sysdate - interval '5' year
will both give you all the rows from the last 5 years (though you would generally want to add a TRUNC
to remove the time portion unless you really care whether a row was created on Feb 8, 2007 in the morning or in the afternoon).
两者都会为您提供过去 5 年的所有行(尽管您通常希望添加 aTRUNC
以删除时间部分,除非您真的关心一行是在 2007 年 2 月 8 日上午还是下午创建的)。
回答by James L.
select * from products
where time > DATE_SUB(NOW(), INTERVAL 5 YEAR)
Date sub will subtract 5 years from now
日期子将从现在减去 5 年