I have a table with integer fields like this:
| Field1 | Field2 | Field3 |
|---|---|---|
| 6 | 1 | 2 |
| 3 | 6 | 2 |
| 7 | 4 | 2 |
| 5 | 6 | 1 |
| 1 | 6 | 2 |
| 5 | 7 | 1 |
- First, I want to look for the max value in field3. It's 2.
- Now, I want to look for the max value in field2, but only in records that have the max value from step 1. It's 6.
- Now, I want to look for the max value in field1, but only in records that have the max value from step 2. It's 3
The result must be:
| Field1 | Field2 | Field3 |
|---|---|---|
| 3 | 6 | 2 |
These numbers are just an example. They can be in range from 0 to max_int.
How to write an SQL query for Firebird 3?
As pointed out by user13964273 in the comments, you can use
order byandfetch:dbfiddle
You can also use the window function
ROW_NUMBER()with the desired order for this:dbfiddle
The solution with
ORDER BYis far simpler. Using a window function likeDENSE_RANKcould make sense if you want to find all matching rows (i.e. if there are multiple rows with the same maximum values).