Justin Grimm got three outs in the eighth and Neil Ramirez pitched a scoreless ninth.
That Samardzija's skid ended at San Francisco — which entered with the best record in the majors — only made it that much sweeter.
The Giants' hottest hitter capitalized on two of the few mistakes Samardzija made. After Pagan reached when Samardzija dropped the ball for an error while covering first base, Sandoval singled with two outs in the first to give the Giants a 1-0 lead.
The Cubs came back in the third on solo shot by Schierholtz, a former Giants outfielder. Sandoval put San Francisco up 3-1 with a golf-like swing on a pitch that looked well below the strike zone in the fourth.
Samardzija hit a tying, two-out double and scored on Emilio Bonifacio's triple during a three-run fifth that put the Cubs in front 4-3.
"The hit by their pitcher kind of broke our back," Giants manager Bruce Bochy said.
Welington Castillo and Barney each hit RBI singles in the sixth. Anthony Rizzo and Luis Valbuena each drove home a run in the seventh to extend Chicago's lead to 8-3 and support Samardzija's effort.
"He deserves to have a lot of wins right now," Schierholtz said, "and it was just nice to get him that one today."
NOTES: The Cubs activated OF Justin Ruggiano from the 15-day disabled list and optioned OF Ryan Kalish to Triple-A Iowa. ... Bochy said he used Huff as a pinch-hitter in the fifth because he was worried that Sanchez (foul tip off mask) and LF Michael Morse (left calf tightness) might need to come out of the game in the late innings. ... Cain is progressing well and the team hopes the right-hander will take his next turn in the rotation Saturday at St. Louis. ... Tim Hudson (4-2, 2.13 ERA) takes the mound for the Giants opposite Chicago's Jake Arrieta (1-0, 2.33) on Tuesday.