问题描述
由于Hive软件的限制,我没有使用RANK(),PARTITION BY和OVER()的奢望。
我想做的是从每个组中检索第一行。
表架构如下:
# Field,Type,Null,Key,Default,Extra
'prod_id','int(11)','NO','PRI',NULL,''
'brand','varchar(20)','YES','',''
'name','varchar(75)',''
'price',''
'cost',''
'shipping_wt','smallint(6)',''
select brand,name,price from
(select brand,price,row_number()
over(partition by brand order by price desc) as rn
from products) as sub
where rn=1;
如果没有上述功能和关键字,怎么办?
解决方法
您可以使用join
和聚合:
select p.*
from products p join
(select p.brand,min(p.price) as min_price
from products p
group by p.brand
) pp
on p.brand = pp.brand and p.price = pp.min_price;
这实际上等效于rank()
而不是row_number()
,但是如果没有重复价格,则是相同的。
不过,我强烈建议您使用窗口功能。它们不仅是标准的,而且是Hive不可或缺的一部分,但它们也应该更快。