Praise be to Allah the Lord of the Worlds. May His peace and blessings be upon our Prophet Mohammad and upon all his family and companions.
In principle, whatever comes first from the perspective of Sharia must be given priority while whatever comes last mustn`t be given priority.
Izz Ibn Abdullsalam (May Allah have mercy on him) said: "It isn`t permissible for anyone, except the ruler and his deputies, to dispose of public funds. However, if this isn`t possible, then those who come in charge next must spend public funds, first things first, as would the ruler or his deputies. " {Qawaid al-Ahkam, V.1:123}. Ibn Jozai (May Allah have mercy on him) said, "First things come first as far as expenditures are concerned." {Al-Kawaneen al-Fiqhiyah, P.147}.
In conclusion, priority must be given in light of necessity and importance. Therefore, if digging the well is more necessary because water is scarce then it should be given priority over the Imam`s residence, but if the Imam`s residence is more necessary, then priority should be given to it.
This issue can be assessed by the mosque`s committee members for they are more aware of the situation and the available funds. Thus, if the funds that the committee has were originally collected in favor of the mosque, then they should be spent on digging the well, but if the funds were collected in favor of building the Imam`s residence then they should be spent on the latter. And Allah the Almighty knows best.