Date Arithmetic with SQL and DB2 for i

2019-07-14 18:42发布

问题:

I am trying to run a SQL query that will update information in a specific table. the problem I am running into is that I need the query to pull today's date, for whatever the date may be when the query is run, and then only pull records going back to years. I then want it to return an AVG of the CUR_CASH_UNITS over that two year time period. I have tried DATEDIFF and DATEADD and those do not appear to work with the system I have because it returns a *libl error. Here is what I have:

Select  Month,
    SSSALESNAM,
    CAT,
    Sum(Units) as Units     
From    DW****.******EG
Inner Join  (Select CAT,
                STORE,
                MONTH(DATE) As Month,
                Sum(CUR_CASH_UNITS) As Units
         From   DW*******.****AT        
         Inner Join (Select CAT,
                            CATNUM
                     From   DW****.*****ST) As Category_List             
        On         DW*******.****AT.CATEGORY_NUMBER=Category_List.CATNUM
        --Where  (((CUR_CASH_UNITS.MONTH(DATE)) Between MONTH(DATE) And (MONTH(DATE)-24MONTH))
        Group by Cat,
                 Store,
                 MONTH(DATE)) As Cash_Units

On          DW****.******EG.SSSTR=Cash_Units.STORE           
Group By    Month,
        SSSALESNAM,
        CAT
Order By    Month,
        SSSALESNAM

The section above that is commented out is just one of my attempts to get the date arithmetic to work. With the Where statement commented out the query executed correctly. The date column in my table is labeled as DATE with a format of YYYY-MM-DD. Kind of new to SQL so I apologize in advance if it is something simple that I am overlooking.

回答1:

I think you want a where clause like the following:

where "date" between current date - 2 years and current date

You need the double quotes because date is a reserved word. The rest is just for getting a date in the past two years.