Skip to content
Advertisement

Mysql Select X rows after specific match

I’m trying to write a select statement in MySQL to get 5 rows after I get my match then sum how many times those numbers were repeated.

Example:

Raw Table

id number
1 1
2 0
3 9
4 14
5 11
6 0
7 3
8 4
9 10
10 9
11 0
12 5
13 3
14 11
15 0

I need to find every row with the number 0, then after that select and show 5 rows after and counting the appearance of the numbers. How can I select the numbers and get the count as a result?

The result of the first select should be like this:

id number
3 9
4 14
5 11
6 0
7 3
7 3
8 4
9 10
10 9
11 0
12 5
13 3
14 11
15 0

The result of the count for every number in the last query.

Number Count
9 2
14 1
11 2
0 3
3 3
4 1
10 1
5 1

Advertisement

Answer

This is a demo to get expected results:

Select numbers:

Count numbers:

Sample data:

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=1fe71080cfb27680eb2a37b721e5de2d

Update for MySQL v5.7


https://dbfiddle.uk/?rdbms=mysql_5.7&fiddle=3be09acab5cd696ec4b01585eb5c32ed

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement