简洁的计算方式:分组内分组

时间:2018-09-17 22:57:36

标签: sql-server group-by

我有一些购买记录数据。想要看到:按merchant分组,每个客户的不同产品的平均数量是多少?

这是我的代码

CREATE TABLE purchases (
    id int IDENTITY,
    merchant varchar(50) NOT NULL,
    customer VARCHAR(50) NOT NULL,
    product VARCHAR(50) NOT NULL,
    amount money
);

INSERT INTO purchases (merchant, customer, product, amount) 
VALUES 
    ('apple', 'John', 'iphone', 100),
    ('apple', 'John', 'macbook', 100),
    ('apple', 'Jessi', 'iphone', 100),
    ('microsoft', 'John', 'surface laptop', 100),
    ('microsoft', 'John', 'surface book', 100),
    ('microsoft', 'Jessi', 'surface book', 100)

-- I can do it with two layers of group by
select merchant
    , avg(cast(ct_product as float)) as avg_number_products_per_customer
from (
    select merchant
        , customer
        , count(distinct product) as ct_product
    from purchases
    group by merchant, customer
) as a
group by merchant

如上所述,我可以使用两层group by来做到这一点,但理想情况下,我只想要一个主group by,这样代码看起来很整洁,而且我可以放置其他sum / {{ 1}},例如:

avg

1 个答案:

答案 0 :(得分:2)

您的查询确实是最好的方法。我将其写为:

select merchant, avg(ct_product * 1.0) as avg_number_products_per_customer
from (select merchant, customer,
            count(distinct product) as ct_product
      from purchases
      group by merchant, customer
     ) mc
group by merchant;

您还可以按照以下方式进行计算:

select merchant,
       count(distinct concat(customer, ':', product)) / count(distinct customer)
from purchases
group by merchant;