Hive:如何 select 中间元素按某列排序

Hive: How to select the middle element order by some column

什么是 select 按某些列排序的中间元素的配置单元查询。

示例:

Name      age
A          10
B          20
C          30

输出:B 20.

中间的元素是列的中位数。有几种方法可以做到这一点。一个可靠的方法是:

select avg(age)
from (select t.*,
             row_number() over (order by age) as seqnum,
             count(*) over () as cnt
      from t
     ) t
where seqnum * 2 in (cnt, cnt + 1, cnt + 2);

这适用于偶数行和奇数行。它确实假设 "age" 是数字(因此 avg() 会起作用)。

您可以使用解析函数 row_number() 和 count() 找到中间行,如下所示:

select name, age
from (
select
    name,
    age,
    row_number() over (order by your_order_by_list) r,
    count(*) over () c
from
    your_table) t
where r = cast((c + 1) / 2 as int);