I have a query like this:
SELECT PlayerID, COUNT(PlayerID) AS "MatchesPlayed", Name, Role, Team,
SUM(Goals) As "TotalGoals", SUM(Autogoals) As "TotalAutogoals",
SUM(...)-2*SUM(...)+2*SUM(...) AS Score, ...
FROM raw_ordered
GROUP BY PlayerID
ORDER BY Score DESC
where in raw_ordered each row describes the performance of some player in some match, in reverse chronological order.
Since I’m grouping by PlayerID what I get from this query is a table where each row provides the cumulative data about some player. Now, there’s no problem with columns with aggregate functions; my problem is with the Team column.
A player may change team during a season; what I’m interested in here is the last Team he played with, so I’d like to have a way to tell SELECT to take the first value met in each group for the Team column (or, in general, for non-aggregate-function columns).
Unfortunately, I don’t seem to find any (easy) way to do this in SQLite: the documentation of SELECT says:
If the expression is an aggregate expression, it is evaluated across all rows in the group. Otherwise, it is evaluated against a single arbitrarily chosen row from within the group.
with no suggestion about how to alter this behavior, and I can’t find between the aggregate functions anything that just takes the first value it encounters.
Any idea?
SQLite does not have a ‘first’ aggregate function; you would have to implement it yourself.
However, the documentation is out of date. Since SQLite 3.7.11, if there is a
MIN()orMAX(), the record from which that minimum/maximum value comes is guaranteed to be chosen.Therefore, just add
MAX(MatchDate)to theSELECTcolumn list.