我想从表格中提取某些东西的最大值(数量(*))。
有效地,我正在努力做的是拉出一个客户最喜欢的品牌。所以他们每年要买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
提前致谢
答案 0 :(得分:1)
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
请记住,如果有多个品牌对某些客户具有相同的数量,那么您最终会得到一条任意记录。如果要获取所有记录,请使用dense_rank()函数:
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 强>
对于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 强>
答案 1 :(得分:0)
或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