MYSQL - Group by limit

前端 未结 3 1824
太阳男子
太阳男子 2020-12-06 16:48

Is there a simple way to LIMIT the GROUP BY results to the top 2. The following query returns all the results. Using \'LIMIT 2\' reduces the overall list to the top 2 entr

3条回答
  •  再見小時候
    2020-12-06 17:23

    I don't think that there is a simple way in MySQL. One way to do this is by generating a row number for each row partitioned in groups by rating_name, and then only select the rows with row_number 2 or less. In most databases you could do this using something like:

    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
    

    Unfortunately, MySQL doesn't support the ROW_NUMBER syntax. You can however simulate ROW_NUMBER using variables:

    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
    

    Result when run on your test data:

    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
    

提交回复
热议问题