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
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1ead615-47f24.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1ead615-47f24.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?