根据日期和n的增量重新启动行号

xpcnnkqh  于 2021-06-25  发布在  Hive
关注(0)|答案(1)|浏览(275)

我有一个包含以下数据的表,这些数据是用日期表生成的

date     day_num (DAY_NUM % 7)
2019-07-09  0   0
2019-07-10  1   1
2019-07-11  2   2
2019-07-12  3   3
2019-07-13  4   4
2019-07-14  5   5
2019-07-15  6   6
2019-07-16  7   0

我基本上想得到一个在0重新开始的周数,我需要帮助找出最后一部分
最终输出如下所示

date     day_num (DAY_NUM % 7) week num
2019-07-09  0   0        1
2019-07-10  1   1        1
2019-07-11  2   2        1
2019-07-12  3   3        1
2019-07-13  4   4        1
2019-07-14  5   5        1
2019-07-15  6   6        1
2019-07-16  7   0        2

这是我到目前为止的sql

select 
SUB.*,
DAY_NUM%7
FROM(
SELECT 
  DISTINCT 
  id_date,
  row_number() over(order by id_date) -1 as day_num 
FROM schema.date_tbl
WHERE Id_date BETWEEN "2019-07-09" AND date_add("2019-07-09",146)
hgb9j2n6

hgb9j2n61#

基于您的查询:

select SUB.*, DAY_NUM%7,
       DENSE_RANK() OVER (ORDER BY FLOOR(DAY_NUM / 7)) as weeknum
FROM (SELECT DISTINCT id_date,
             row_number() over(order by id_date) -1 as day_num 
      FROM schema.date_tbl
      WHERE Id_date BETWEEN "2019-07-09" AND date_add("2019-07-09", 146)
     ) x

相关问题