数据:stock.csv
tradedate | tradetime | stockid | buyprice | buysize | sellprice | sellsize |
---|---|---|---|---|---|---|
交易日期 | 交易时间 | 股票id | 买入价格 | 买入数量 | 卖出价格 | 卖出数量 |
要求(录屏):
1)创建hive数据表
2)利用自定义函数UDF,计算股票’204001’:每天所有买入价格和卖出价格的最大值、每天所有买入价格和卖出价格的最小值
3)利用hql语句,计算股票’204001’每天每分钟的平均交易价格。
4)利用窗口函数,对股票’131800’的所有买入价格按照从大到小排序,并生成序号。
实现步骤:
1)创建数据表(也可创建分区表)
create table stock(
tradedate string,
tradetime string,
stockid string,
buyprice double,
buysize int,
sellprice double,
sellsize int)
row format delimited fields terminated by ',' stored as textfile;
load data local inpath '/home/hadoop/stock.csv' into table stock;
2)利用自定义函数UDF,计算股票’204001’:每天所有买入价格和卖出价格的最大值、每天所有买入价格和卖出价格的最小值
自定义函数:
package hive_test;
import org.apache.hadoop.hive.ql.exec.UDF;
public class priceMax extends UDF{
public Double evaluate(Double a, Double b) {
if(a==null)
a=0.0;
if(b==null)
b=0.0;
if(a>=b){
return a;
}else{
return b;
}
}
}
public class priceMin extends UDF{
public Double evaluate(Double a, Double b) {
if(a==null)
a=0.0;
if(b==null)
b=0.0;
if(a>=b){
return b;
}else{
return a;
}
}
}
打包后在hive中执行:
add jar /home/hadoop/priceMax.jar;
add jar /home/hadoop/priceMin.jar;
create temporary function priceMax as 'hive_test.priceMax';
create temporary function priceMin as 'hive_test.priceMin';
select tradedate,max(priceMax(buyprice,sellprice)) maxprice,min(priceMin(buyprice,sellprice)) minprice from stock where stockid='204001' group by tradedate;
3)利用hql语句,计算股票’204001’每天每分钟的平均交易价格。
select stockid,tradedate,substring(tradetime,0,4),sum(buyprice+sellprice)/(count(*)*2) from stock where stockid='204001' group by stockid, tradedate,substring(tradetime,0,4);
4)利用窗口函数,对股票’131800’的所有买入价格按照从大到小排序,并生成序号。
select tradedate,buyprice,row_number() over(order by buyprice desc) from stock where stockid='131800'
#排序函数用row_number()/rank()/dense_rank()都可以