This question already has answers here:
Get top n records for each group of grouped results
                                
                                    (10个回答)
                                
                        
                                3年前关闭。
            
                    
假设我有这张桌子。

users|amount
------------
User1|  500
User1|  400
User1|  300
User1|  200
User1|  100
User2|  500
User2|  400
User2|  300
User2|  200
User3|  300
User3|  200


我想为每个用户显示最多3个交易。示例中给出的结果应该是这样。

users|amount
------------
User1|  500
User1|  400
User1|  300
User2|  500
User2|  400
User2|  300
User3|  300
User3|  200


有没有办法在SQL(MySQL)中做到这一点?我应该怎么做?

最佳答案

你可以这样尝试

SELECT
    users, amount
FROM (SELECT
    users, amount,
    ROW_NUMBER() OVER (PARTITION BY users ORDER BY amount DESC) AS rn
FROM yourtable) AS a
WHERE a.rn <= 3

关于mysql - 每个用户最多显示3个交易,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39703297/

10-09 08:30