Вы можете использовать FIRST_VALUE
:
SELECT A, row_num,
CASE WHEN FIRST_VALUE(row_num) OVER(PARTITION BY A ORDER BY row_num) = row_num
THEN 1 ELSE 0 END AS first_row,
CASE WHEN FIRST_VALUE(row_num) OVER(PARTITION BY A ORDER BY row_num DESC)=row_num
THEN 1 ELSE 0 END AS last_row
FROM tab
ORDER BY a, row_num;
ДБ <> Fiddle demo
Выход:
+----+----------+------------+----------+
| a | row_num | first_row | last_row |
+----+----------+------------+----------+
| 1 | 1 | 1 | 1 |
| 2 | 1 | 1 | 0 |
| 2 | 2 | 0 | 1 |
| 3 | 1 | 1 | 1 |
+----+----------+------------+----------+