SQL 查询按客户使用过的唯一商家的数量对客户进行排名

SQL query to Rank Customers by the number of unique merchants they have used

我正在尝试根据客户使用过的唯一商家的数量对客户进行排名。

请求你帮我解决 SQL 代码。

您可以从下方查看数据link: https://www.kaggle.com/ntnu-testimon/banksim1#bs140513_032310.csv

试试这个,使用 MySQL 8.0 中的 dense_rank() window 函数。这是 DEMO

没有子查询

select
    customer,
    count(distinct merchant) as total_unique_merchants,
    dense_rank() over (order by count(distinct merchant)) as rnk
from myTable
group by
    customer

带子查询

select
    customer,
    total_unique_merchants,
    dense_rank() over (order by total) as rnk
from
(
    select
        customer,
        count(distinct merchant) as total_unique_merchants
    from myTable
    group by
        customer
) val

您可以使用window函数:

select cust, count(distinct merchant) as uniue_merchants,
       dense_rank() over (order by count(distinct merchant) desc) as seq
from table t
group by cust;