SQL 查询最佳实践以生成 Table 的 1 次购买者与经常购买者的百分比

SQL Query Best Practice to Generate A Percentage Table of 1 Time buyer buyers Versus Frequent Buyers

我有一个名为 client 的 table,如下所示:

Client Price
============
A      123
A      389
A      34
B      4
B      5
C      33

比如客户A在本店购买了3次[第一次123$第二次389$第三次34$]。其他客户的逻辑相同...

我尝试获得一个百分比 table 来获得只购买了 1 次的客户和购买超过 1 次的客户。结果应该是

Category    Percentage
=======================
1timebuyer  0.3333
2timeOrMore 0.66666 

确实客户A买了3次,客户B买了2次,所以3个客户中有2个属于2timeOrMore类别。因此 2timeOrMore 代表 0.6666 [2/3] 的买家和 1timebuyer 0.3333 [1/3]

在 mysql 1 SQL 仅查询 中执行此操作的最佳方法是什么?

我认为您需要两个级别的聚合。里面的是:

select client, count(*) as cnt
from clients c
group by client;

然后我会像这样旋转所有计数:

select cnt, count(*), min(client), max(client)
from (select client, count(*) as cnt
      from clients c
      group by client
     ) c
group by cnt
order by cnt;

但是你想要更简单的东西:

select (case when cnt = 1 then '1' else '>1' end) as grp,
       count(*) as num_clients,
       count(*) / sum(count(*)) over () as ratio
from (select client, count(*) as cnt
      from clients c
      group by client
     ) c
group by grp;
order by cnt;