MADRID — The ousted leader of Spain’s main opposition Socialist Party, Pedro Sánchez, made a remarkable comeback on Sunday, winning re-election as party leader only seven months after stepping down in defeat.

Mr. Sánchez won 50.2 percent of the votes, defeating Susana Díaz and Patxi López, who won 39.9 percent and 9.9 percent of the votes, according to preliminary results released shortly before midnight here on Sunday, with 99.2 percent of the votes counted. Almost 188,000 party members were eligible to take part in the Socialist primary.

Despite his unexpectedly clear-cut victory, Mr. Sánchez faces an uphill struggle to revive a party that he led to two successive election defeats in which the Socialists received their lowest percentage of votes ever.

The two elections — in December 2015 and June 2016 — were both won by the conservative Popular Party of Prime Minister Mariano Rajoy, but each time without any party coming close to a parliamentary majority. As a result, Spain was left in a political stalemate for almost a year, during which the main party leaders bickered over how to form a coalition government. In October, Mr. Sánchez was ousted by members of his own party, who did not want to risk a third election. His removal cleared the way for Mr. Rajoy to start a second term as prime minister.