Select TOP 3 of every month

Asked

Viewed 77 times

-1

I need to return the top 3 of a query each month:

select distinct  mes, rubrica, count(*) qtd
from boletins
group by mes, rubrica
order by mes asc, qtd desc;

This query above returns about 30 lines for each month, but only need the first 3 as below:

inserir a descrição da imagem aqui

  • add limit 3 at the end of the consultation

1 answer

1

Here is a suggestion to test using the Row_number function to number the lines per month and in descending order of quantity:

with CTE_RN as
(
    select 
        mes, 
        rubrica, 
        count(*) qtd,
        row_number() over(partition by mes order by count(*) desc) as RN
    from boletins 
    group by 
        mes, 
        rubrica 
)

select mes, rubrica, qtd
from CTE_RN
where RN <= 3
order by mes asc, qtd desc

I hope it helps

  • I am using Mysql Workbench, and it does not seem to support WITH and ROW_NUMBER Error Code: 1064. You have an error in your SQL syntax; check the manual that Corresponds to your Mysql server version for the right syntax to use near 'CTE_RN as ( select mes, rubric, Count() Qtd, ' at line 1 0,156 sec Error Code: 1064. You have an error in your SQL syntax; check the manual that Corresponds to your Mysql server version for the right syntax to use near '(Partition by mes order by Count() desc) as RN from boletins group by ' at line 5 0,156

  • this query looks more like PL/SQL

  • Fabiana, which version of Mysql are you using? The use of CTE and the Row_number function are available as of version 8.0

Browser other questions tagged

You are not signed in. Login or sign up in order to post.