I have the following table:

enter image description here

I need to find the row with the maximum product_count. This is the SQL that I have tried but it doesn't give the correct result:

SELECT product_id, MAX(product_count)
GROUP BY product_id

EDIT:

SELECT product_id, MAX(product_count) as max_count
FROM
(
    SELECT product_id, COUNT(product_id) as product_count
    FROM wp_stvp_voting_data
    GROUP BY product_id
) as T1
GROUP BY product_id

1 Answers

3
Tim Biegeleisen On Best Solutions

One simple option is to use LIMIT:

SELECT product_id, COUNT(product_id) AS product_count
FROM wp_stvp_voting_data
GROUP BY product_id
ORDER BY COUNT(product_id) DESC
LIMIT 1;

If you needed to cater to the possibility that there might be more than one record tied for the maximum product count, and you wanted to return all ties, then we could try using a subquery:

SELECT product_id, COUNT(product_id) AS product_count
FROM wp_stvp_voting_data
GROUP BY product_id
HAVING COUNT(product_id) = (SELECT MAX(cnt) FROM (
                               SELECT COUNT(*) AS cnt
                               FROM yourTable
                               GROUP BY product_id
                           ) t)

If you are using MySQL 8+, then we would be able to take advantage of ROW_NUMBER:

SELECT product_id, product_count
FROM
(
    SELECT product_id, COUNT(product_id) AS product_count,
        ROW_NUMBER() OVER (ORDER BY COUNT(product_id) DESC) rn
    FROM yourTable
    GROUP BY product_id
) t
WHERE rn = 1;

Replace ROW_NUMBER with RANK if you want all ties for first place.