如何Assert窗口中的当前行是最后一行?

hgtggwj0  于 2021-06-27  发布在  Hive
关注(0)|答案(3)|浏览(428)

如果我有一个问题 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
gg58donl

gg58donl1#

你可以用 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;

db<>小提琴演示
输出:

+----+----------+------------+----------+
| a  | row_num  | first_row  | last_row |
+----+----------+------------+----------+
| 1  |       1  |         1  |        1 |
| 2  |       1  |         1  |        0 |
| 2  |       2  |         0  |        1 |
| 3  |       1  |         1  |        1 |
+----+----------+------------+----------+
tyg4sfes

tyg4sfes2#

这将显示总计数:

COUNT(*) OVER ...

您还可以执行以下操作:

ROW_NUMBER() OVER (.... ORDER BY ... DESC)

按降序排序意味着1=您的最后一条记录

zlwx9yxi

zlwx9yxi3#

我会做:

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

相关问题