Skip to content
Advertisement

Get List of Last 15 Days Date in SQL

Could SQL get list of date of last 15 days date in a single query?

We can get today date with

select current_date()

We also can get last 15 days date with

select date_add(current_date(), -15)

But how to show the list of last 15 days date? For example the output is

2020-05-17, 
2020-05-18, 
2020-05-19, 
2020-05-20, 
2020-05-21, 
2020-05-22, 
2020-05-23, 
2020-05-24, 
2020-05-25, 
2020-05-26, 
2020-05-27, 
2020-05-28, 
2020-05-29, 
2020-05-30, 
2020-05-31

Advertisement

Answer

In Hive or Spark-SQL:

select date_add (date_add(current_date,-15),s.i) as dt 
  from ( select posexplode(split(space(15),' ')) as (i,x)) s

Result:

2020-05-18
2020-05-19
2020-05-20
2020-05-21
2020-05-22
2020-05-23
2020-05-24
2020-05-25
2020-05-26
2020-05-27
2020-05-28
2020-05-29
2020-05-30
2020-05-31
2020-06-01
2020-06-02

See also this answer.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement