Home > OS >  Extract all the data from current date to 2 years back in SQL
Extract all the data from current date to 2 years back in SQL

Time:07-28

The below table having 1000 rows but here let's consider 3 rows:

Date B C
2022-07-24 Selena 1234
2021-02-01 Katy 6789
2020-04-30 Snoop 4324

I want to extract all the data from last two years to current date. For instance, Today's date is : 28-07-2022

I want the data from 28-07-2020 to 28-07-2022

My code should always take today's date to last 2 year every time it runs.

CodePudding user response:

an example query (mysql)

select *
from mytable 
where mycol_dt >= DATE_SUB(CURDATE(), INTERVAL 24 MONTH)

Looks like GCP uses "CURRENT_DATE()" though instead of "CURDATE()" . A minor tweak. I'll leave it as-is to be mindful of those that may be using other databases.
In this example the DATE_SUB clause takes in a data and INTERVAL parameters, and returns the date that represents the difference. Depending on what granularity you need you may need to use a DAY interval or perhaps YEAR.
(Leap year logic may also affect what you get back, and may mean you'll need to delve into using TSQL or some high-level language logic to customize the query. That depends on your requirements.)

  • Related