SQL first three data for each category

there is a user table User (id, email), and a payment record table Transaction (id, transaction_type, transaction_amount) to find out the email and total payment amount of the three users with the highest total payment in each payment category

Apr.01,2021

using these two keywords should help you solve the problem: desc limit3;


SELECT user.id, user.email, SUM(transaction.transaction_amount) as total_payment
FROM User user LEFT JOIN Transaction transaction ON user.ID = transaction.user_id
GROUP BY transaction.transaction_type
order by total_payment desc limit 0,3

idea, group according to the payment category, calculate the total payment of each user under each payment category, and take the first three

according to the descending order of the total payment.

the specific sentence will not be written, let's talk about the train of thought.
mysql higher version, supports window functions, like this:

row_number over (partition by transaction_type order by amount desc)

then according to the return value of the function < = 3, as a Filter condition

if it is not supported, mysql has @ variable, which is probably used as follows. You need to sort by transaction_type amount in sql to determine whether transaction_type is equal to the previous one, and reset the value of @ rownum. Finally, Filter is carried out according to the value of rank in the following statement.
search with the keyword "mysql row number" to find a complete example.

SELECT t.*, 
       @rownum := @rownum + 1 AS rank
  FROM YOUR_TABLE t, 
       (SELECT @rownum := 0) r
Menu