簡體   English   中英

蜂巢:如何通過某些列選擇中間元素順序

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

什么是配置單元查詢,以選擇按某列排序的中間元素。

例:

Name      age
A          10
B          20
C          30

輸出: B 20

您可以使用解析函數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);

中間元素是列的中位數。 有幾種方法可以做到這一點。 一種可靠的方法是:

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);

這適用於偶數和奇數行。 它確實假定“年齡”是數字(因此avg()將起作用)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM