2

I'm looking to pull the max(count(*)) of something from a table.

Effectively what i'm trying to do is pull out a customers favourite brand. So they buy 300 bars of soap a year but I'd like to know which their favourite is. So the max(count(brand_id) basically.

I was thinking of doing it like this:

    SELECT
 transaction.customer_id,
 max(occ) 
 FROM
 (  SELECT 
    transaction.customer_id,
    count(transaction.brand_id) as occ,
    FROM
    transaction

    GROUP BY
    transaction.customer_id,

) AS foo
GROUP BY
transaction.customer_id

Thanks in advance

2 Answers 2

2

you can do it like this:

with cte as (
    select customer_id, brand_id, count(*) as cnt
    from test1
    group by customer_id, brand_id
)
select distinct on (customer_id)
    customer_id, brand_id, cnt
from cte
order by customer_id, cnt desc

Keep in mind, that if there more than one brand with equal count for some customer, you'll end up with one arbitrary record. If you want to get all records, use dense_rank() function:

with cte1 as (
    select customer_id, brand_id, count(*) as cnt
    from test1
    group by customer_id, brand_id
), cte2 as (
    select
        customer_id, brand_id,
        dense_rank() over(partition by customer_id order by cnt desc) as rn
    from cte1
)
select customer_id, brand_id
from cte2
where rn = 1

sql fiddle demo

For PostgreSQL 8.3:

select distinct on (customer_id)
    customer_id, brand_id, cnt
from (
    select customer_id, brand_id, count(*) as cnt
    from test1
    group by customer_id, brand_id  
) as c
order by customer_id, cnt desc;

sql fiddle demo

Sign up to request clarification or add additional context in comments.

2 Comments

@QuinnOlive yes, check the sql fiddle
My PostgreSQL is 8.3 unfortunately :/
0

or like this

 with cte as (
    SELECT 
        transaction.customer_id,
        count(transaction.brand_id) as occ,
        FROM
        transaction

        GROUP BY
        transaction.customer_id
    )

    select max(occ) from cte 

3 Comments

Will this work in PostgreSQL? I keep getting an error on the "AS"
@QuinnOlive: yes that should work with any supported version. CTEs where introduced with 8.4.
Ahhh. Bugger. My postgreSQL server is 8.3 :/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.