I'll split the logic into separate steps to make it easier.
First, let's see where the last occurrence of number 21 was, for example:
SELECT reg
FROM tabelaMaisOuMenosAssim
WHERE 21 IN (num0,num1,num2,num3,num4,num5)
ORDER BY reg DESC
LIMIT 1;
Once you get this record, just count how many there are after it. In your example, we would have received 3
as a return.
To know how many came after (you can use >=
if you want to include the current line):
SELECT COUNT(*) AS atrasado WHERE reg > 3
If you are using some support language, this can be done with two queries and use of variables.
Putting the two together
We can do a subquery to get the result in a single operation:
SELECT COUNT(*) AS atrasado
FROM tabelaMaisOuMenosAssim
WHERE reg >= (
SELECT reg
FROM tabelaMaisOuMenosAssim
WHERE 21 IN (num0,num1,num2,num3,num4,num5)
ORDER BY reg DESC
LIMIT 1
);
See working on SQL Fiddle .
If you are going to use this feature constantly
You can create a FUNCTION
that is part of the database instead of using the entire query every time you need to get a value:
CREATE FUNCTION pegaAtrasado(numero int)
RETURNS int
RETURN (
SELECT COUNT(*)
FROM tabelaMaisOuMenosAssim
WHERE reg >= (
SELECT reg
FROM tabelaMaisOuMenosAssim
WHERE numero IN (num0,num1,num2,num3,num4,num5)
ORDER BY reg DESC
LIMIT 1
)
);
How to use (simple like this):
SELECT pegaAtrasado( 21 );
SELECT pegaAtrasado( 5 );
SELECT pegaAtrasado( 1 );
See working on SQL Fiddle .