sql >> Database >  >> RDS >> Mysql

MySQL-groep op opeenvolgende verschijningen

Op voorwaarde dat uw tabel er als volgt uitziet:

"id";"year";"team"
"1";"2000";"AAA"
"2";"2001";"CCC"
"3";"2002";"CCC"
"4";"2003";"BBB"
"5";"2004";"AAA"
"6";"2005";"AAA"
"7";"2006";"AAA"

Deze zoekopdracht zou het lukken:

SELECT a.year AS start
     , MIN(c.year) AS end
     , MIN(c.year)-a.year+1 AS total
     , CONCAT_WS('-', a.year, IF(a.year = min(c.year), NULL, min(c.year))) as start_end
     , a.team
  FROM 
     ( SELECT x.year, x.team, COUNT(*) id
         FROM results x
         JOIN results y
           ON y.year <= x.year
        GROUP BY x.id
     ) AS a
  LEFT JOIN 
     ( SELECT x.year, x.team, COUNT(*) id 
         FROM results x
         JOIN results y
           ON y.year <= x.year
        GROUP BY x.id
     ) AS b ON a.id = b.id + 1 AND b.team = a.team
  LEFT JOIN  
     ( SELECT x.year, x.team, COUNT(*) id 
         FROM results x
         JOIN results y
           ON y.year <= x.year
        GROUP BY x.id
     ) AS c ON a.id <= c.id AND c.team = a.team
  LEFT JOIN 
     ( SELECT x.year, x.team, COUNT(*) id 
         FROM results x
         JOIN results y
           ON y.year <= x.year
        GROUP BY x.id
     ) AS d ON c.id = d.id - 1 AND d.team = c.team
WHERE b.id IS NULL AND c.id IS NOT NULL AND d.id IS NULL
GROUP BY start;

Mogelijk vindt u de Common Queries Tree handig om deze problemen op te lossen (controleer de antwoorden voor "Vind vorige en volgende waarden in een reeks") :p.




  1. pg.rb segmentatiefout [Mojave-upgrade]

  2. Verhoogt het instellen van NOT NULL op een kolom in postgresql de prestaties?

  3. Oracle In-Memory kosten

  4. FOUT:nul-lengte gescheiden identifier op of nabij LINE 1:DELETE FROM regionen WHERE regionen. =$1