首页 > 解决方案 > 在 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,即:

蜂巢

我怎样才能做到这一点?

标签: hivehiveqlwindow-functions

解决方案


使用 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

推荐阅读