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

MySQL - Mengembalikan nomor X dari setiap GROUP BY

Coba seperti di bawah ini, buat nomor baris untuk setiap grup dan kemudian batasi nomor baris di bawah ini saya menampilkan 2 hasil per grup.

   Select
    `marka_name`, `model_name`, `kuzov`, `mileage`, `year`, `rate`from
    (

    SELECT
     @row_num := IF(@prev_value=main.Model_Name,@row_num+1,1) AS RowNumber,
                main.*,
    @prev_value := main.Model_Name
            FROM
                main,
      (SELECT @row_num := 1) x,
          (SELECT @prev_value := '') y
            WHERE
                (
                    (marka_name = 'SUBARU' AND model_name = 'IMPREZA' AND (kuzov = 'GC8' OR kuzov = 'GF8')) OR
                    (marka_name = 'MAZDA' AND model_name = 'RX-7' AND kuzov = 'FD3S') OR
                    (marka_name = 'MITSUBISHI' AND model_name = 'LANCER' AND (kuzov = 'CN9A' OR kuzov = 'CP9A')) OR
                    (marka_name = 'NISSAN' AND model_name = 'SKYLINE' AND (kuzov = 'ER34' OR kuzov = 'BCNR33')) OR
                    (marka_name = 'NISSAN' AND model_name = 'SILVIA' AND kuzov = 'S14') OR
                    (marka_name = 'TOYOTA' AND model_name = 'CELICA' AND kuzov = 'ST205') OR
                    (marka_name = 'TOYOTA' AND model_name = 'ARISTO' AND kuzov = 'JZS161') OR
                    (marka_name = 'MITSUBISHI' AND model_name = 'DELICA' AND (kuzov = 'PE8W' OR kuzov = 'PD8W' OR kuzov = 'PF8W'))
                )
                AND
                (rate != 'RA' AND rate != 'RR' AND rate != 'A1' AND rate != 'A' AND rate != 'R' AND rate >= '3')
                AND
                (mileage >= 0 AND mileage <= 150000)
                AND
                (year >= 1990 AND year <= 1998)
            ORDER BY
                model_name,
                mileage ASC,
                rate DESC) A where A.RowNumber<=2

Untuk mendapatkan lebih dari 2 catatan per grup, cukup ubah yang terakhir di mana Klausul seperti jika Anda mengumpulkan 10 hasil per grup daripada. tulis di mana A.RowNumber<=10

Demo Sql Fiddle




  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Pemicu MySQL sebelum Masukkan nilai Memeriksa

  2. Kesalahan koneksi SSL saat menghubungkan ke RDS MySQL dari Django

  3. Nilai string salah dalam python+django+Mysql

  4. while($row =mysql_fetch_array($query)) tidak berfungsi untuk kedua kalinya

  5. Parsing JSON ke mySQL