【问题标题】:How to return the top 3 spending customers per country?如何返回每个国家/地区的前 3 名消费客户?
【发布时间】:2021-07-14 05:25:33
【问题描述】:

我正在尝试为每个国家/地区的前 3 名消费客户返回如下表格:

customer_id country spend
159 China 45
152 China 8
159 China 21
160 China 6
161 China 9
162 China 93
152 China 3
168 Germany 91
169 Germany 101
170 Germany 38
171 Germany 17
154 Germany 11
154 Germany 50
167 Germany 63
168 Germany 1
153 Japan 7
163 Japan 58
164 Japan 44
153 Japan 19
164 Japan 10
165 Japan 15
166 Japan 24
153 Japan 105

我尝试了下面的代码,但它没有返回正确的结果。

SELECT customer_id, country, spend FROM (SELECT customer_id, country, spend,
            @country_rank := IF(@current_country = country, @country_rank + 1, 1)
             AS country_rank,
            @current_country := country
       FROM table1
       ORDER BY country ASC, spend DESC) ranked_rows
       WHERE country_rank<=3;

由于一些客户也是回头客,我想确保考虑的是每位客户的支出总和。

【问题讨论】:

    标签: sql database greatest-n-per-group mysql-5.6 sqlfiddle


    【解决方案1】:

    您似乎正在使用 MySQL。如果您运行的是版本 8 或更高版本,则只需在此处使用 ROW_NUMBER()

    WITH cte AS (
        SELECT *, ROW_NUMBER() OVER (PARTITION BY country ORDER BY spend DESC) rn
        FROM table1
    )
    
    SELECT customer_id, country, spend
    FROM cte
    WHERE rn <= 3;
    

    【讨论】:

    • 我正在使用只能升级到 MySQL 5.6 的 SQL Fiddle
    • @gerg 然后使用支持 MySQL 8 的 DBFiddle:dbfiddle.uk/?rdbms=mysql_8.0
    • 感谢您的提示!该命令似乎有效,只是它两次返回相同的客户 ID,但中国的收入不同,而不是将它们相加为 1 并返回该国家/地区的 3 个唯一客户 ID。我正在尝试使用 GROUP BY 语句,但我认为我没有将其放在正确的位置,因为它返回错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-10
    • 1970-01-01
    • 2019-09-28
    • 2013-01-21
    • 1970-01-01
    • 2023-03-05
    相关资源
    最近更新 更多