It is important to read this tale of the sheep and the goats in the context not only of the rest of this chapter, but also in the context of the rest of Scripture.
Taken out of context, this passage could be interpreted to mean that we can earn our salvation through good works. The rest of Scripture shows that this is not true.
So, what is happening here? The division of the sheep and the goats is one image of the judgement carried out by the Son of Man. We have just read two others: the judgement of the unprepared virgins, and the judgement of the unfaithful servants. Each image of the judgement has a different emphasis. In the first, the oil is often thought to represent the Holy Spirit. Are we born again of the Spirit? Are we continually filled with the Spirit in our walk with the Lord?
The second image of the judgement is one of faithful and unfaithful servants. What have we done with the blessing that God has poured out on us? Have we prioritised him above all other things?
The third, with the sheep and the goats, is about the fulfilment of the Law as Jesus distilled it. The prepared virgins and the faithful servants have shown that they love God before all other things. Here Jesus is looking for those who have loved their neighbours as themselves.
When Jesus comes to judge all the nations, he will be looking for those who have received him, and who bear the fruit of that through the way they have lived their lives. It will not be enough to say, “Lord! Lord!” if our lives do not reflect the truth of our salvation. Nor will it be enough to say, “But I was a good person!” if we have not come before him in repentance.
Jesus could have used many different examples to explain the coming judgement, but he chose these three. We can understand from his choices that these things are important to him, including taking care of the poor, the sick and the weak. We may not earn salvation through these good works, but they are expected of us anyway, and what we do for the least of his brothers, we do for him.