Need to select top 5 rows for each id based on desc values of a particular column , value and find the subtotal of that column . for e.g (Tried creating the situation , actual table structure is large )
ID VALUE
1 2
1 3
1 4
1 5
1 6
1 7
1 8
2 9
2 10
2 11
2 12
2 13
2 14
Output Expected
ID VALUE
1 8
1 7
1 6
1 5
1 4
TOTAL 30
2 14
2 13
2 12
2 11
2 10
TOTAL 60
I could select top 5 rows using a code like this ;
@cust_rank := IF(@current_cust = id, @cust_rank + 1, 1) AS cust_rank,
@current_cust := id
and then selecting top 5
Also ,I could subtotal using code like this ;
SELECT id, value FROM source
UNION
SELECT NULL,SUM(value) FROM source
GROUP BY id ORDER BY id;
See Question&Answers more detail:osI need to merge both requirements .