postgresql表中的值分布

postgresql表中的值分布,sql,postgresql,distribution,Sql,Postgresql,Distribution,我有一个类似Postgresql的表 user_name | product_name ----------+------------- tom | candle bill | candle bill | candle tom | pen bill | pen 我想知道蜡烛销售的分布情况,即有多少人只买了一支蜡烛,有多少人买了两支蜡烛,等等 我曾尝试使用Postgreql窗口函数,但我头痛:) 杰弗里 select quan

我有一个类似Postgresql的表

user_name | product_name       
----------+-------------
      tom | candle
     bill | candle
     bill | candle
      tom | pen
     bill | pen
我想知道蜡烛销售的分布情况,即有多少人只买了一支蜡烛,有多少人买了两支蜡烛,等等

我曾尝试使用Postgreql窗口函数,但我头痛:)

杰弗里

select quantity, count(*)
from (
    select user_name, count(*) as quantity
    from t
    where product_name = 'candle'
    group by user_name
) s
group by quantity
order by quantity