This is going to be a very long query. What you need is for every system_id that have more than 5 records you want to delete the record that are less than ranking 3.
I'm going to seperate the queries and use names for them at the end.
1_ ranking_query: abriviation is RQ
In mysql there is no rownum or something like that hope this query return the records ranked from ghe first to the last.
SELECT
@rank := @rank + 1 as rank,
id,
system_id,
value
FROM table_name, (select @rank:=0) as rt
order by system_id, value desc
this will rank every record in your table and the main benefit is the record with the same system_id will be after each other in desc order
system_id value rank
1. 10. 1
1. 9. 2
1. 7. 3
1. 5. 4
1. 3. 5
1. 2. 6
2. 12. 7
2. 10. 8
3. 11. 9
........
......
3. 1. 15
In this example for system_id 1 we need to keep only the three first (1,2,3) record same thing for system_id 3 (9,10,11)
2_ filter_query. Abriviation is: FQ
Because you want to delete based on count 5 we need this extra query
SELECT
system_id
FROM table_name
GROUP BY system_id
having count(*) > 5
result:
system_id
1
3
4_ third_query abriviation: RQD
a query to know which rank should we start do delete from for every system_id in mysql we need to rewrite the first query again but here i'm going to use Abriviation to keep the answer short.
SELECT
system_id,
min_rank + 3 from_rank
FROM (
SELECT
RQ2.system_id,
min(RQ2.rank) as min_rank
FROM (rank_query) RQ2
GROUP BY system_id) RS
so for the same example the we going to have this result
system_id. from_rank
1. 4
2. 9 -- this record will be removed by the filter_query
3. 12
FINAL QUERY:
so we need to delete record that exist in filter query and the ranking is bigger than from_rank.
DELETE FROM table_name WHERE
id in (
SELECT
RQ.id
FROM
rank_query RQ INNER JOIN filter_query FQ ON rq.system_id = FQ.system_id
INNER JOIN third_query RQD ON RQ.rank >= RQD.from_rank)
I hope this idea work sorry for any syntax error i used my phone to answer i like this kind of query