Mysql
 sql >> Teknologi Basis Data >  >> RDS >> Mysql

Grup MySQL berdasarkan penampilan berturut-turut

Asalkan tabel Anda terlihat seperti ini :

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

Kueri ini harus berhasil :

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;

BTW Anda mungkin menemukan Pohon Pertanyaan Umum berguna untuk memecahkan masalah ini (periksa jawaban untuk "Temukan nilai sebelumnya dan berikutnya secara berurutan") :p.




  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Wordpress SQL:dapatkan kategori dan tag posting

  2. mysql terlalu lama untuk menyisipkan baris

  3. Bisakah prosedur/fungsi tersimpan mengembalikan tabel?

  4. Bagaimana cara mengisi database hanya sekali sebelum metode @Test dalam tes musim semi?

  5. Kondisi MySQL JIKA