1

我正在寻找从表中提取某些东西的 max(count(*)) 。

实际上,我正在尝试做的是拉出客户最喜欢的品牌。所以他们每年购买 300 块肥皂,但我想知道他们最喜欢哪块。所以 max(count(brand_id) 基本上。

我正在考虑这样做:

    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

提前致谢

4

2 回答 2

1

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

于 2013-11-08T08:46:09.390 回答
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 
于 2013-11-08T08:44:29.943 回答