Date Arithmetic with SQL and DB2 for i

╄→尐↘猪︶ㄣ 提交于 2019-12-11 03:06:27

问题


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.



来源:https://stackoverflow.com/questions/14320057/date-arithmetic-with-sql-and-db2-for-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!