如何有条件地为每个用户选择一行?

时间:2021-04-17 09:26:37

标签: mysql window-functions

我有以下查询:

select count(1) num, business_id, user_id FROM `pos_transactions` 
group by user_id, business_id
order by user_id

它返回这个:

+--------+-------------+---------+
|  num   | business_id | user_id |
+--------+-------------+---------+
| 3      | 503         | 12      |
| 7      | 33          | 12      |
| 1      | 771         | 13      |
| 2      | 86          | 13      |
| 1      | 772         | 13      |
| 4      | 652         | 14      |
| 4      | 567         | 14      |
+--------+-------------+---------+

我只需要为每个 user_id 选择一行,即具有更大 num 值的那一行。如果用户的所有 num 值都相同,则应随机选择其中之一(即用户 #14)。所以,这是预期的结果:

+--------+-------------+---------+
|  num   | business_id | user_id |
+--------+-------------+---------+
| 7      | 33          | 12      |
| 2      | 86          | 13      |
| 4      | 567         | 14      |
+--------+-------------+---------+

知道我该怎么做吗?


我想该解决方案将与每个用户的 limit 1 相关。但我不知道应该如何编写查询。

我想要做的就是让每个 user_id 的表都是唯一的,逻辑是选择具有更大 num 的行。

1 个答案:

答案 0 :(得分:0)

使用MAX()FIRST_VALUE()窗口函数:

SELECT DISTINCT 
       MAX(COUNT(*)) OVER (PARTITION BY user_id) num, 
       FIRST_VALUE(business_id) OVER (PARTITION BY user_id ORDER BY COUNT(*) DESC) business_id, 
       user_id 
FROM pos_transactions 
GROUP BY user_id, business_id
ORDER BY user_id