Bicycles SQL Solutions
- What riders belong to the team ‘Os Velozes’? (name)
SELECT name FROM rider WHERE team = 'Os Velozes'
- What rider won the ‘Porto - Aveiro’ stage? (name)
SELECT name FROM rider JOIN classification USING (ref) JOIN stage USING (num) WHERE description = 'Porto - Aveiro' AND position = 1
- What riders ciclistas raced the ‘Coimbra - Lisboa’ stage and what was their final position? Order the answer by their position. (name, position)
SELECT name, position FROM rider JOIN classification USING (ref) JOIN stage USING (num) WHERE description = 'Coimbra - Lisboa' ORDER BY position
- How many riders are there in each team? (team, total)
SELECT team, COUNT(*) FROM rider GROUP BY team
- What is the total sum of times of each rider? (name, total)
SELECT name, SUM(time) FROM rider JOIN classification USING (ref) GROUP BY ref
- What team, or teams, has a smaller sum of its riders total times? (team)
SELECT team, SUM(time) as total FROM rider JOIN classification USING (ref) GROUP BY team HAVING SUM(time) = ( select min(sum_time) from ( SELECT SUM(time) as sum_time FROM rider JOIN classification USING (ref) GROUP BY team ) );
- What is the average time in each stage? (description, average)
SELECT description, AVG(time) FROM stage JOIN classification USING (num) GROUP BY num
- What stage, or stages, had the smaller average time? (description)
SELECT description FROM stage JOIN classification USING (num) GROUP BY num HAVING AVG(time) = ( select min(avg_time) from ( SELECT AVG(time) as avg_time FROM stage JOIN classification USING (num) GROUP BY num ) );
- What was the time difference between the first and second rider in each stage? (description, difference)
SELECT first.description, strftime('%s', second.time) - strftime('%s', first.time) as difference FROM (SELECT * FROM stage JOIN classification USING (num) WHERE position = 1) AS first JOIN (SELECT * FROM stage JOIN classification USING (num) WHERE position = 2) AS second USING (num);
- What stage had the biggest time difference between the first and second rider to finish it, what rider won that stage and with how much lead time. (description, name, difference).
SELECT first.description, first.name, strftime('%s', second.time) - strftime('%s', first.time) as difference FROM ( SELECT * FROM stage JOIN classification USING (num) join rider USING (ref) WHERE position = 1 ) AS first JOIN ( SELECT * FROM stage JOIN classification USING (num) WHERE position = 2 ) as second on first.num = second.num WHERE strftime('%s', second.time) - strftime('%s', first.time) = ( select max(difference) from ( SELECT strftime('%s', second.time) - strftime('%s', first.time) as difference FROM classification AS first JOIN classification AS second USING (num) WHERE first.position = 1 AND second.position = 2 ) );
(Credits: André Restivo https://web.fe.up.pt/~arestivo)