如果我有一个ROW_NUMBER() OVER
查询,如何获取此窗口中总行的输出,或者最后一行作为布尔值?
我想在结果中创建两列,并为窗口中的第一行和最后一行创建一个布尔值。
A | ROW_NUMBER
---
1 | 1
2 | 1
2 | 2
3 | 1
TO
A | ROW_NUMBER | FIRST | LAST
---
1 | 1 | 1 | 1
2 | 1 | 1 | 0
2 | 2 | 0 | 1
3 | 1 | 1 | 1
您可以使用
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;
数据库<>小提琴演示
输出:
+----+----------+------------+----------+
| a | row_num | first_row | last_row |
+----+----------+------------+----------+
| 1 | 1 | 1 | 1 |
| 2 | 1 | 1 | 0 |
| 2 | 2 | 0 | 1 |
| 3 | 1 | 1 | 1 |
+----+----------+------------+----------+
这为您提供了总数:
COUNT(*) OVER ...
您还可以执行以下操作:
ROW_NUMBER() OVER (.... ORDER BY ... DESC)
按降序排序表示 1 = 您的最后一条记录
我会这样做:
select
a,
row_number,
case ra = 1 then 1 else 0 end as first,
case rd = 1 then 1 else 0 end as last
from (
select
a,
row_number,
row_number() over(partition by a order by row_number) as ra,
row_number() over(partition by a order by row_number desc) as rd
from my_table
) x
order by a