您如何断言WINDOW中的当前行是最后一行?

时间:2019-01-03 15:40:03

标签: sql hive amazon-athena presto

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

3 个答案:

答案 0 :(得分:1)

这将为您提供总数:

COUNT(*) OVER ...

您也可以这样做:

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

降序排列意味着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;

db<>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 |
+----+----------+------------+----------+

答案 2 :(得分: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