Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying last 5 years

I want to query all products sold in the last 5 years.
It is possible to do it like this:

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?

like image 631
Evgenij Reznik Avatar asked Feb 08 '12 16:02

Evgenij Reznik


People also ask

How to get the last 5 years of data in Excel?

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).

How do I calculate the last quarter of 2011?

If today's date is 2/2/2012, you’ll see items for the last quarter of 2011. Year ( [SalesDate])*4+DatePart ("q", [SalesDate]) = Year (Date ())*4+DatePart ("q",Date ())+1

How to convert 1826 days to 5 years?

This is indirectly addressed by @JustinCave's answer, but 1826 days does not consistently equal 5 years (a 5 year span can contain 1 or 2 leap years). That's why it's better to use operators that deal in whole months or years (which are consistent). SELECT * FROM products WHERE date_column >= add_months ( sysdate, -12*5 )

How do I add 5 years to a date?

if you want from 1st Jan 5 years ago DATEADD (year, DATEDIFF (year, 0, GETDATE ()) - 5, 0) if you want 5 years ago today DATEADD (YEAR, -5, DATEADD (day, DATEDIFF (day, 0, GETDATE ()), 0)) Add some details... Tab to the formatting toolbar with Alt/Option + F10. If inside toolbar, press ESC to return to editor.


1 Answers

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).

like image 172
Justin Cave Avatar answered Nov 15 '22 18:11

Justin Cave