简体   繁体   中英

Selecting a date range in db2 SQL

I am trying to select a date range in db2 SQL. The date range would be current day -7 days to current day - 1 day. I would like to select all records within that range. I have tried to do this by declaring a variable for each date:

CREATE OR REPLACE VARIABLE v_date7 varchar(10)
Set v_date7= select current date - 7 days from sysibm.sysdummy1

This will error out because

Keyword SET not expected

I have tried adding a ; to the end of the first line, but that then errors out because the ; is not vaild.

Try a Recursive Common Table Expression (RCTE) like this:

WITH T (D) AS 
(
VALUES CURRENT DATE - 1 day
  UNION ALL
SELECT D - 1 day
FROM T
WHERE D > CURRENT DATE - 7 day
)
SELECT D
FROM T;

To create and set a global variable in the database

create or replace variable sevendaysago date 
      default(current_date - 7 days)         

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM