How to query table using window function in MySql 8.0

Advertisements

How can I transform first table in the second table using a Mysql 8.0 window function query?

The records are orderd by col1. On col2 every record should have the smallest value (1) until a bigger value is encountered (10) then every record after that should have 10 until a bigger value is encountered (20) and so on…

I tried a window query MIN(col2) OVER (ORDER BY col1) and also tried ROW_NUMBER() but cannot achieve the result.

fiddle

col1 col2
1 1
3 1
11 10
12 10
15 1
20 10
21 1
22 20
22 10
25 20
26 10
col1 col2
1 1
3 1
11 10
12 10
15 10
20 10
21 10
22 10
22 20
25 20
26 20

>Solution :

SELECT col1,
       MAX(col2) OVER (ORDER BY col1) col2
FROM example

fiddle

Leave a ReplyCancel reply