注:参考文章:
HiveSql一天一个小技巧:如何不借助其他任何外表,产生连续数值_hive生成连续数字-CSDN博客文章浏览阅读1.3k次。0 需求描述输出结果如下所示:12345...1001 问题分析方法一:起始值(start)+步长(diff)=结束值(end)select split(space(5), ' ')+----------------------+| _c0 |+----------------------+| ["","","","","",""] |+----------------------+select posexplode(spl_hive生成连续数字https://blog.csdn.net/godlovedaniel/article/details/124135352
0 需求描述
生成1-10的连续值
1 数据分析
方式一:posexplode炸裂函数,生成下角标pos, 再利用起始值start + pos(步长) = 结束值end
需要借助函数 split 和 space
split(分割字符串)
- 语法:split(string str, string pat)
- 返回值:array
- 说明:按照pat分隔符分割 字符串str, 返回分割后的字符串数组
- 举例:select split('adgncf','n') --> ["adg","cf"]
space:空格字符串函数
- 语法: space(int n)
- 说明:返回长度为5的空格字符串
- 举例:select length(space(5)) ---> 5
select split(space(5),'')
输出结果为:
select posexplode(split(space(5),''))
输出结果为:
因此, 生成1-10的连续值的代码如下:
selectid_start + tmp.pos as id
from (select1 as id_start,10 as id_end) tlateral view posexplode(split(space(id_end - id_start),'')) tmp as pos, val
方式二:利用row_number() over()排名函数生成id序列
selectrow_number() over () as id
from (select explode(split(space(9), ''))) t
2 小结
上述案例主要用到posexplode炸裂函数(带下角标pos)或row_number()函数,生成连续的数值。这种思路可以借鉴到 【用户间断连续登陆】类型的 题型中,手动填补间断的天数。
Hive炸裂函数文章见:
HiveSQL题——炸裂函数(explode/posexplode)_hive exolode-CSDN博客文章浏览阅读1.2k次,点赞28次,收藏13次。HiveSQL题——炸裂函数(explode/posexplode)_hive exolodehttps://blog.csdn.net/SHWAITME/article/details/135941286?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522170754345516800225566168%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fblog.%2522%257D&request_id=170754345516800225566168&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~blog~first_rank_ecpm_v1~rank_v31_ecpm-1-135941286-null-null.nonecase&utm_term=%E7%82%B8%E8%A3%82%E5%87%BD%E6%95%B0&spm=1018.2226.3001.4450