如何使用Hive sql在表的每个组中获得10个结果?

时间:2017-03-27 12:56:08

标签: sql hive

我有一张桌子

enter image description here

我想按类对数据进行分组,然后每个类挑选出两个数据,无论是否排序。

然后得到这样的结果。

enter image description here

如何编写sql?

1 个答案:

答案 0 :(得分:1)

使用select sum(count) as count, week_start, week_end from ( select t1.count, date_sub(location_date, interval (datediff(t1.location_date, t2.min_date) % 7) day) week_start, date_sub(location_date, interval (datediff(t1.location_date, t2.min_date) % 7) - 6 day) week_end from location t1 cross join (select min(location_date) as min_date from location) t2 where t1.tagCode = 24901 and t1.xLocation between 278 and 354 and t1.yLocation between 239 and 426 and t1.locationDate >= DATE_SUB('2017-03-01 00:00:01',INTERVAL 7 day) and t1.locationDate <= '2017-03-27 23:59:59' ) t3 group by week_start, week_end

row_number()

如果您想要两个特定行 - 例如两个得分最高或得分最低的行 - 那么请调整select t.* from (select t.*, row_number() over (partition by class order by class) as seqnum from t ) t where seqnum <= 2; 子句。