In the Song Dynasty (960-1279) there was a joker called Sun Shan. One year he went to take the imperial examination, and came bottom of the list of successful candidates. Back in his hometown, one of his neighbours asked him whether the neighbour's son had also passed. Sun Shan said, with a smile: "Sun Shan was the last on the list. Your son came after Sun Shan."
Later, people used this idiom to indicate failing in an examination or competition.