Skip to content
Advertisement

SQL to find local count max per primary key

I have a table with PK CustomerId + type. Each customer has a few types.

For each customer I want to get type which repeated the most for this customer.

I’ve tried to create a column "count" but I want to get the local maxs, and not a global max for the whole col.

Is there a native way to do so?

Advertisement

Answer

to get type which repeated the most for this customer

You need to group by CustomerId,type. With row_number you can partition by CustomerId and order by the COUNT(type).

Try:

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=8e8657dfa08ff170ed3eaf5e335b3582

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement