title: Find the nearest match that could add up to zero in SAS
body: <p>I am using SAS for research. My question is how to find the nearest match in the same column. Please see the following for a quick illustration. I am new to SAS programming, and only have a preliminary guess that proc sql might do the work. What I am doing now is manually adjusting - it is painful and especially so for over 3,000 observations.</p>
  
  <p><img src="https://i.stack.imgur.com/bBtJg.jpg" alt="The data I have"></p>
  
  <p>I want to find the nearest "Value" match that could add up to zero. For example, for firm AA in 1st quarter 2000, I want to match the nearest two numbers that could add up to 100. I don't want the 50 for firm AA in 2002Q2 nor firm BB 2000Q4. In addition, I also struggle with the case for firm BB, and have no idea how to perform the matching: the two negative numbers add up to -200, the two positive numbers add up to +200, and they maybe in same or different years. To help you understand better, please find the following table for what I have in mind at the end of the day:</p>
  
  <p><img src="https://i.stack.imgur.com/VDBtg.jpg" alt="The data I want"></p>
  
  <p>For the BB case, it can be 2001Q3 "-100" matched to "50" in 2000Q4, it is also fine if it matches to "100" in 2001Q1 - the order doesn't matter. Thanks in advance! Any help is really appreciated!</p>
  
  <p>Regards,
  Michael</p>