Limit number of occurrences of Group By

3

I have to search in a data table of an advertiser, I need to group by advertiser according to the most viewed, separated by date.

I wanted to limit group by , how?

Example table:

id       visualizacoes       data
485            19            20/05/2105
485            68            11/03/2105
121            45            05/04/2105
485            20            20/05/2105
370            37            26/05/2105
225            81            20/05/2105
485            75            07/03/2105
485            11            20/05/2105
485            46            20/05/2105
370            23            16/04/2105
370            15            09/05/2105
121            7             21/04/2105
680            10            20/05/2105
370            68            26/05/2105
370            92            26/05/2105

I want to group by id_anunciante and add views with the same date, but I wanted to limit up to 3 records per advertiser.

Initial Query:

SELECT *, SUM(visualizacoes) AS total_visu 
FROM anunciante 
GROUP BY id,data
    
asked by anonymous 28.05.2015 / 14:44

2 answers

3

By default MySQL does not do this, but we can improvise.

Assuming your original query is

SELECT id, data, SUM(visualizacoes)
FROM tabela
GROUP BY id, data 
ORDER BY id, data DESC;

Place your query in a subquery, an extra column will be added which will count the redo of certain id :

SELECT id, data, totalVisualizacoes,
@currcount := IF(@currvalue = id, @currcount + 1, 1) AS rank,
@currvalue := id FROM (
    SELECT id, data, SUM(visualizacoes) AS totalVisualizacoes
    FROM tabela
    GROUP BY id, data 
    ORDER BY id, data DESC;
) AS totais;

Finally, make the final query that will filter the number of occurrences:

SELECT id, data, totalVisualizacoes FROM (
    SELECT id, data, totalVisualizacoes,
    @currcount := IF(@currvalue = id, @currcount + 1, 1) AS rank,
    @currvalue := id FROM (
        SELECT id, data, SUM(visualizacoes) AS totalVisualizacoes
        FROM tabela
        GROUP BY id, data
        ORDER BY id, data DESC
    ) AS totaisPorData
) AS totalLimitado
WHERE rank <= 3;

Example on slqfiddle .

Reference

    
28.05.2015 / 15:25
0

I was having a very similar problem and I could not resolve it using the gmsantos answer , however I found another answer very similar by the user Salman A (link to the answer) , that's when I was able to understand how the count of occurrences of a value in a specific field, it worked 100% for me!
Pay attention to the first line where you have:

SET @currcount = NULL, @currvalue = NULL;

This line must always be present for the occurrence count to work. (If you are editing the sql in phpmyadmin this line will disappear if you execute the query and click edit again)

Note: My problem was to select the last 20 offers of each company in the bank

    
05.12.2017 / 00:12