hive - 在 Hive 的 row_number() 中按窗口函数按顺序对分区进行自定义排序
问题描述
我有一个带有标识符列的表id
和另一个带有字符串值column_b
的列,我想对其进行客户订购column_b
。假设它column_b
由值A, B, C, D组成。
可以在 Hive 中用于 row_number() over() 的语法是:
SELECT id, column_b, row_number() over(partition by id order by column_b) as row_id
FROM some_table
示例请参见此处的示例
但是,我想做自定义排序而column_b
不是字母排序。上面的语法会产生类似的东西:
相反,我想使用 order 明确地按 column_b 排序A, C, D, B
,即:
我怎样才能做到这一点?
解决方案
使用 case 语句明确指定顺序。您可以在 中使用其他标量函数order by
:
SELECT id, column_b,
row_number() over(partition by id order by case column_b
when 'A' then '1'
when 'C' then '2'
when 'D' then '3'
when 'B' then '4'
--add more cases
--for example other values sort
--in natural order
else column_b
--or use constant
--to make sure
--everything else is greater than 4
--like this else concat('5',column_b)
end
) as row_id
FROM some_table
您也可以在子查询中计算订单列并在窗口中使用它,它的工作方式相同:
SELECT id, column_b,
row_number() over(partition by id order by orderby) as row_id
FROM (select t.*,
case column_b
when 'A' then '1'
when 'C' then '2'
when 'D' then '3'
when 'B' then '4'
else concat('5',column_b)
end orderby
from some_table t
) s
推荐阅读
- javascript - 如何删除最后一个数组映射的分隔符图标?
- apache-kafka - Kafka GlobalStateStore 可以从不同的处理器拓扑访问吗?
- python - 在对 YouTube 频道进行网页抓取期间,循环未完成,无法提取频道中所有视频的数据
- python - 如何在 DRF 中使用 api 在 python 中进行身份验证
- python - 与断言在同一行上的 Pytest 条件语句不起作用
- reactjs - 何时将回调传递给 useState 设置器实际上会有所作为?
- angular - 离子:在模板中的对象上运行循环的生产构建失败
- flutter - 元素类型 Color 不能分配给列表类型 Color
- javascript - firebase:emulators:Start :术语“firebase:emulators:Start”未被识别为 cmdlet、函数、脚本文件或可运行程序的名称
- html - 无法删除我网站上的多余空白