As group winners and securing a spot in the FIFA World Cup knockout rounds, Japan overcame a goal deficit to defeat European powerhouse Spain 2-1 in the group’s final match.

Spain and Japan advanced to the tournament’s knockout round despite losing the last league game of their group.

Alvaro Morata’s goal in the 11th minute put Japan in the hole during a chaotic night of two games at the Khalifa International Stadium, trailing 1-0 at the break.

But in the second half, the Samurai Blue came roaring back, scoring twice in as many minutes. Ritsu Doan’s goal for coach Hajime Moriyasu in the 48th minute brought the score even, and three minutes later, Ao Tanaka’s goal gave the team the lead.

Japan began their tournament campaign with a 2-1 victory against four-time champion Germany but fell to Costa Rica. Japan has set a goal of reaching the tournament’s last-eight stage.

Spain, on the other side, began the match by crushing Costa Rica 7-0 before drawing 1-1 with Germany.

In the other game, which was played at Al Bayt Stadium in Al Khor, Germany defeated Costa Rica 4-2 in a thrilling six-goal game that was refereed by the first all-female on-field refereeing panel at a men’s World Cup.

With just four points from three games, they finished with the same record as Spain, but La Roja qualified due to a superior goal differential. The winning effort was insufficient.

Japan completed with six points from two victories and a defeat, and Spain was eliminated after losing to Japan 2-1.

Germany is eliminated in group play for the second straight tournament. It hasn’t been enough on one of those evenings.

Germany’s failure to advance in the World Cup for the second time in a row is a remarkable decline for a national team that won the tournament in 2014, placed third in 2010 and 2006, and finished second in 2002.

Both Group E and Group F had unexpected group winners on Thursday. Japan will take on Croatia in the round of 16 on Monday after emerging victorious from Group E. Morocco will face Spain on Tuesday in the Group F championship game.

The World Cup continues on Friday, and following the conclusion of the games in Groups G and H, the round of 16 will be determined.

The last-eight goal that Moriyassu set for himself at the beginning of the competition is now within reach.