Hi all,

I have a sample data that shows the donation amount of a contributor. It is a combination of different possible scenarios. I would like to obtain the variable TotAmt as shown. Any suggestions on how I could obtain the variable would be much appreciated.

The data includes the following variables:
ContribID is Contributor ID
fyear is the fiscal year of the company
cyclesgroup2 indicates the fiscal year cycle based on fiscal year of the company, where 2007-2008 is in cycle 1, 2009-2010 is in cycle 2, 2011-2012 is in cycle 3 and etc)
yrcontrib is the year in which the contributor made the contribution
cyclesgroup is donation year cycle. Similar to cyclesgroup2 but it is based on donation year (yrcontrib)
Amount is the donation amount for that year
unique is an indicator whether the transaction is unique
TotAmt is the total amount donated by the contributor in the most recent donation cycle (cyclesgroup)


Code:
* Example generated by -dataex-. To install: ssc install dataex
clear
input str12 ContribID double fyear float(cyclesgroup2 yrcontrib cyclesgroup Amount) byte unique float TotAmt
"H3002162339" 2016 5 2008 1 200 1 250
"H3002162339" 2016 5 2010 2 250 1 250
"H3002162339" 2016 5 2017 6 215 1 250
"H3002162340" 2016 5 2008 1 200 1 215
"H3002162340" 2016 5 2010 2 250 1 215
"H3002162340" 2016 5 2015 5 215 1 215
"H3002162341" 2016 5 2008 1 200 1 250
"H3002162341" 2016 5 2010 2 250 1 250
"H3002162341" 2016 5 2015 5 215 0 250
"H3002162350" 2016 5 2008 1 200 1 465
"H3002162350" 2016 5 2015 5 215 1 465
"H3002162350" 2016 5 2016 5 250 1 465
"H3002162351" 2015 5 2008 1 200 1 250
"H3002162351" 2016 5 2010 2 250 1 250
"H3002162351" 2017 6 2017 6 215 1 215
end

As you can see the TotAmt for Contributor H3002162339 is $250 because the closest donation year/cycle to the fiscal year is 2010 which has a donation amount (Amount) of $250. Donation in 2017 cannot be considered as the closest since the donation has not occurred during the company's 2016 fiscal year.
Contributor H3002162340 has TotAmt of $215 because the closest donation year/cycle to the fiscal year is now 2015 (most recent donation before/on the fiscal year)
Contributor H3002162341 has TotAmt of $250 and not $215 (although the latter has the closest donation year to the fiscal year) because the observation is not unique (unique=0).
Contributor H3002162350 has TotAmt of $465 because the closest donation years/cycle to the fiscal year are 2015 & 2016 (cyclesgroup=5).
Contributor H3002162351 has TotAmt of $250 for 2015 & 2016 fiscal year, taking the donation amount in 2010 (closest donation year/cycle). But TotAmt is $215 for 2017 fiscal year, taking the donation amount in 2017 of $215.

As mentioned earlier, I would like to obtain the variable TotAmt as shown. Any suggestions on how I could obtain the variable would be much appreciated. Please let me know if I have not explained it clearly and more info is required.

Thank you in advance.
Regards