Saya tidak berpikir bahwa ada cara sederhana di MySQL. Salah satu cara untuk melakukannya adalah dengan membuat nomor baris untuk setiap baris yang dipartisi dalam grup berdasarkan rating_name, dan kemudian hanya memilih baris dengan row_number 2 atau kurang. Di sebagian besar basis data, Anda dapat melakukan ini menggunakan sesuatu seperti:
SELECT * FROM (
SELECT
rating_name,
etc...,
ROW_NUMBER() OVER (PARTITION BY rating_name ORDER BY good) AS rn
FROM your_table
) T1
WHERE rn <= 2
Sayangnya, MySQL tidak mendukung ROW_NUMBER
sintaksis. Namun Anda dapat mensimulasikan ROW_NUMBER
menggunakan variabel:
SELECT
rating_name, id_markets, good, neutral, bad
FROM (
SELECT
*,
@rn := CASE WHEN @prev_rating_name = rating_name THEN @rn + 1 ELSE 1 END AS rn,
@prev_rating_name := rating_name
FROM (
SELECT
rating_name,
id_markets,
SUM(COALESCE(rating_good, 0)) AS good,
SUM(COALESCE(rating_neutral, 0)) AS neutral,
SUM(COALESCE(rating_bad, 0)) AS bad
FROM zzratings
WHERE rating_year = YEAR(CURDATE()) AND rating_week = WEEK(CURDATE(), 1)
GROUP BY rating_name, id_markets
) AS T1, (SELECT @prev_rating_name := '', @rn := 0) AS vars
ORDER BY rating_name, good DESC
) AS T2
WHERE rn <= 2
ORDER BY rating_name, good DESC
Hasil saat dijalankan pada data pengujian Anda:
france 1 2 0 0 france 2 1 0 0 ireland 1 4 2 0 ireland 21 3 1 0 poland 1 3 1 0 poland 2 1 0 0