I have a table with a column called "IP", and I would like to create another column in the same table "YTD_IP" which would give the cumulative year-to-date sum of "IP" (innings pitched) for any given game in a year reflecting the sum of innings pitched in games (rows/events) that preceded it in the same season. Once there is a change in year, I'd like the sum to start at 0 again.
Here is a sample of data of columns "PIT_ID", "YEAR_ID", "IP", and what I'd like to see the "YTD_IP" column look like:
Pit_ID YEAR_ID IP YTD_IP
aased001 1977 9.0000 9
aased001 1977 9.0000 18
aased001 1977 7.0000 25
aased001 1977 5.0000 30
aased001 1977 6.3333 36.3333
aased001 1977 6.3333 42.6666
aased001 1977 7.0000 49.6666
aased001 1977 6.0000 55.6666
aased001 1977 9.0000 64.6666
aased001 1977 9.0000 73.6666
aased001 1977 5.0000 78.6666
aased001 1977 6.3333 84.9999
aased001 1977 7.3333 92.3333
aased001 1978 4.3333 4.3333
aased001 1978 7.0000 11.3333
aased001 1978 6.3333 17.6666
aased001 1978 3.3333 20.9999
I've put together the following code:
ALTER TABLE starting_pitcher_game_log ADD COLUMN YTD_IP VARCHAR(255);
SET YTD_IP:= 0;
SELECT a.IP, b.YEAR_ID
IF(@prevYEAR_ID != YEAR_ID,IP,@YTD_IP+IP) AS IP,
@prevYEAR_ID=YEAR_ID
FROM starting_pitcher_game_log
But it's not right as it gets the following error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF(@prevYEAR_ID != YEAR_ID,IP,@YTD_IP+IP) AS IP,
@prevYEAR_ID=YEAR_ID
' at line 2
Is there a way to make sure that it accommodates future games that will be played?
Any help would go a long way.
Hi Darwin,
Can you share code that could work for a temporarily invoked column as well as code for a permanent one that could create a cumulative sum field? In particular, I would like to create another column in a table called "YTD_IP" which would give the cumulative year-to-date sum of "IP" (innings pitched) from the beginning of a season up to any given game in that season reflecting the sum of innings pitched by a given pitcher in games (rows/events) that preceded the given game + the innings pitched in that game. Once there is a change in season, I'd like the sum to start at 0 again.
Thank you in advances in for your help.