Not sure how to phrase this question, but I want an aggregate query applied to multiple rows. Hopefully an example should make this easier. Assuming I have the following data:
player | year | games
-------------------------
ausmubr01 | 2006 | 139
ausmubr01 | 2007 | 117
bondsba01 | 2006 | 130
bondsba01 | 2007 | 126
stairma01 | 2006 | 26
stairma01 | 2006 | 77
stairma01 | 2006 | 14
stairma01 | 2007 | 125
And for each player in each year, I want to calculate their "career year", i.e. the number of years they've been playing:
player | year | games | cyear
--------------------------------
ausmubr01 | 2006 | 139 | 1
ausmubr01 | 2007 | 117 | 2
bondsba01 | 2006 | 130 | 1
bondsba01 | 2007 | 126 | 2
stairma01 | 2006 | 26 | 1
stairma01 | 2006 | 77 | 2
stairma01 | 2006 | 14 | 3
stairma01 | 2007 | 125 | 4
It would be natural to express this transformation as SELECT player, year, games, year - min(year) + 1 as cyear FROM baseball GROUP by player
but because of the rules for aggregate queries the expression is only evaluated once for each group:
player | year | games | cyear
--------------------------------
ausmubr01 | 2006 | 139 | 1
bondsba01 | 2006 | 130 | 1
stairma01 | 2006 | 26 | 1
How can I overcome this problem in general (i.e. not just for this case but whenever I want to perform an arithmetic operation combining an existing column and a single per-group number computed with an aggregate function)?