Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save LeeZee1/f6af93ec133930b54cf10126cad2ad43 to your computer and use it in GitHub Desktop.
Save LeeZee1/f6af93ec133930b54cf10126cad2ad43 to your computer and use it in GitHub Desktop.
creates row_number column that restarts at 1 at the start of a new year or new starting pitcher, which is necessary in order to create a meaningful season-to-date park factor column using the code for creating this season-to-date full park factor column.
DROP PROCEDURE IF EXISTS starting_pitcher_AL_NL_std_lg_FIP;
CREATE PROCEDURE starting_pitcher_AL_NL_std_lg_FIP()
BEGIN
DECLARE gdate DATE;
DECLARE YEARID INT;
DECLARE lgID CHAR (2);
DECLARE HR INT;
DECLARE walks INT;
DECLARE HitBP INT;
DECLARE K INT;
DECLARE in_pit REAL;
DECLARE conFIP VARCHAR (255);
DECLARE accum_ip REAL;
DECLARE accum_walks_a REAL;
DECLARE accum_HR REAL;
DECLARE accum_HBP REAL;
DECLARE accum_K REAL;
DECLARE stdFIP REAL;
DECLARE prev_year YEAR(4);
DECLARE end_of_cursor BOOLEAN;
DECLARE no_table CONDITION FOR SQLSTATE '42S02';
DECLARE c1 CURSOR FOR
SELECT Game_Date, YEAR_ID, lg_ID, lg_HR_a, lg_walks_a, lg_HBP, lg_strike_outs, lg_innings_pitched, cFIP
FROM NL_AL_lg_starting_pitcher_stats
ORDER BY lg_ID, YEAR_ID, Game_Date;
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET end_of_cursor := TRUE;
SET end_of_cursor := FALSE; -- reset
SET prev_year := 0; -- reset control-break
OPEN c1;
fetch_loop: LOOP
FETCH c1 INTO gdate, YEARID, lgID, HR, walks, HitBP, K, in_pit, conFIP;
IF end_of_cursor THEN
LEAVE fetch_loop;
END IF;
-- check control-break conditions
IF YEAR(gdate) != prev_year THEN
SET accum_ip := 0.0;
SET accum_walks_a := 0;
SET accum_HR := 0;
SET accum_HBP := 0;
SET accum_K := 0;
SET prev_year := YEAR(gdate);
END IF;
SET accum_ip := accum_ip + in_pit;
SET accum_walks_a := accum_walks_a + walks;
SET accum_HR:= accum_HR + HR;
SET accum_HBP := accum_HBP + HitBP;
SET accum_K := accum_K + K;
IF (accum_ip) = 0 OR (in_pit)=0 THEN
SET stdFIP := 0;
ELSE
SET stdFIP := ((accum_HR*13)+(3*(accum_walks_a+accum_HBP))-(2*accum_K))/accum_ip+conFIP;
END IF;
UPDATE NL_AL_lg_starting_pitcher_stats
SET std_FIP =stdFIP
WHERE lg_ID = lgID
AND YEAR_ID = YEARID
AND Game_Date = gdate;
END LOOP;
CLOSE c1;
END
$$
DELIMITER ;
UPDATE starting_pitcher_stats JOIN
(select starting_pitcher_stats.*,
(@rn := if(@sy = concat_ws(':', Starting_Pitcher, YEAR_ID), @rn + 1,
if(@sy := concat_ws(':', Starting_Pitcher, YEAR_ID), 1, 1)
)
) as rn
from starting_pitcher_stats CROSS JOIN
(select @rn := 0, @sy := '') params
order by Starting_Pitcher, YEAR_ID, Game_Date, Game_Number
) sp2
on sp2.Starting_Pitcher = starting_pitcher_stats.Starting_Pitcher AND
sp2.YEAR_ID = starting_pitcher_stats.YEAR_ID AND
sp2.Game_Date = starting_pitcher_stats.Game_Date AND
sp2.Game_Number=starting_pitcher_stats.Game_Number
set starting_pitcher_stats.row_number = sp2.rn;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment