Skip to content
Advertisement

How to identify pattern in SQL

This is my table. It does consist of A,B and C columns. Only one column value will be true at one time.

Sample Table data

My task is to identify pattern based on latest five rows. For example latest five rows

I need to search entire table to find whenever these five values were repeated.

If they were repeated, what was the next value avilable for these pattern and show how many times does A, B and C values were found after the pattern.

How this can be done in SQL? I am using oracle 11g. Thanks.

Advertisement

Answer

You can convert your a, b, c value to a trinary number and then calculate a value for that row and the previous 4 as if the trinary values for the rows comprised a 5-digit trinary number and then use analytic functions to find the next occurrence and to count the occurrences:

Which, for the sample data:

Outputs:

ID A B C ROW_AFTER_NEXT_MATCH NUM_MATCHES
1 1 0 0 0
2 1 0 0 0
3 0 1 0 0
4 1 0 0 0
5 0 1 0 1
6 0 0 1 12 2
7 1 0 0 13 2
8 0 1 0 1
9 1 0 0 1
10 0 1 0 1
11 0 0 1 2
12 1 0 0 2
13 1 0 0 1
14 1 0 0 1
15 1 0 0 1
16 1 0 0 18 5
17 1 0 0 19 5
18 1 0 0 20 5
19 1 0 0 21 5
20 1 0 0 5

db<>fiddle here

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