sql >> Base de Datos >  >> RDS >> Mysql

¿Liga de fútbol complicada? ¿Ordenamiento dinámico en MySQL?

Hagámoslo paso a paso:

Selecciona los partidos ganados en casa y el marcador en casa:

   SELECT COUNT(*) as wins, SUM(G.home_score) as score FROM games G WHERE 
      G.team_id = T.team_id #See 3. query and you'll understand
      G.home_score > away_score

Llamemos a este resultado INICIO_JUEGOS.

Seleccione los juegos ganados y la puntuación de los juegos fuera de casa:

SELECT COUNT(*) as wins, SUM(G.away_score) as score FROM games G
WHERE 
  G.team_id = T.team_id #See 3. query and you'll understand
  G.away_score > G.home_score

Llamemos a este resultado AWAY_GAMES.

Seleccione el total de juegos ganados y la puntuación total:

   SELECT (A.wins + H.wins) AS total_wins, (A.score + H.score) AS total_score FROM
   (AWAY_GAMES) AS A, (HOME_GAMES) AS H, teams T 
   ORDER BY total_wins, total_score

==> Junte todo sustituyendo AWAY_GAMES y HOME_GAMES:

SELECT (A.wins + H.wins) AS total_wins, (A.score + H.score) AS total_score FROM 
  (SELECT COUNT(*) as wins, SUM(G.away_score) as score FROM games G
   WHERE 
     G.team_id = T.team_id #See 3. and you'll understand
     G.away_score > G.home_score) AS A, 

   (SELECT COUNT(*) as wins, SUM(G.home_score) as score FROM games G 
   WHERE 
      G.team_id = T.team_id #See 3. and you'll understand
      G.home_score > away_score) AS H, 

   teams T
   ORDER BY total_wins, total_score