【发布时间】: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