I’m writing a program for a running contest using SQLite database, and I have to determine teams from the finish data. There are schools taking part of the contest, and one team consist of four(exactly four) people from one school. A school can have more than one team. The team position is determined by the sum of the members positions. The contestants are stored in one table with their finish position name and school.
Can it be done by SQL query or should I solve it in code?
Example:
pos name school pos name school
1 person1 foo 1 person1 foo
2 person2 foo 2 person2 foo
3 person3 bar 6 person6 foo
4 person4 bar 8 person8 foo
5 person5 bar -> 3 person3 bar
6 person6 foo 4 person4 bar
7 person7 bar 5 person5 bar
8 person8 foo 7 person7 bar
9 person9 foo
10 person10 foo
11 person11 bar
I know there is nothing like ROW_NUMBER() OVER… in SQLite, but I cannot find anything about something similar to a CROSS APPLY.
If there is something equivalent to a CROSS APPLY, then you can do the following. (EDIT: I noticed the requirement for schools to be able to have multiple teams. This solution would only work with one team per school. You will need a recursive CTE and ROW_NUMBER as far as I can tell, otherwise—which are not available in SQLite to my knowledge)
If not, then you would probably have to use a while loop and temp tables to fill this. If that is the case, then there is no real gain from using the SQL and I would suggest going the code route.
EDIT:
However, this is the temp table solution as was requested. You need the inner while since you could have multiple teams within the school (something I had disregarded before and makes the CROSS APPLY solution not work without a recursive CTE and ROW_NUMBER, which has been edited to acknowledge)