简体   繁体   中英

Check value exist in previous month in SQL

I have two table XYZ and ABC

create table #abc(id int, value int, dates date)
create table #xyz(id int, value int, dates date)

insert into #xyz values(1,10,'2017/02/01')
Insert into #xyz values(2,10,'2017/05/01')

Insert into #abc values(1,10,'2017/01/01')
Insert into #abc values(1,20,'2017/02/01')
Insert into #abc values(2,4,'2017/01/01')
Insert into #abc values(2,5,'2017/04/01')

XYZ
ID  Value   Dates
1   10  2017/02/01
2   10  2017/05/01

ABC         
ID  Values  Dates   ExpectedResult
1   10  2017/01/01  20
1   20  2017/02/01  0
2   4   2017/01/01  0
2   5   2017/04/01  15

i want to check if table ABC having (Month - 1 ) value comparing with table XYZ. Uniqueness of table is identified by ID and Date . For eg-> Table XYZ id-1 is having date 2017/02/01 ie February data and my ABC table ID-1 is having 2017/01/01 ie January data then XYZ value + ABC value ie 20 is the expected result.

Could you please tell me how do we compare month in this scenario.

You need to use the DATEADD function provided by MS SQL to compare dates, for example

WHERE XYZ.Date = DATEADD(MONTH, -1, ABC.Date)

Have a look at this link on w3schools for a detailed description

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