hive面试题之三 求最高气温
比如:2010012325表示在2010年01月23日的气温为25度。
需求:使用Hive实现以下两个需求:
1、求出每一年的最高温度(年份,最高温度)
2、求出每一年的最高温度是那一天(日期, 最高温度)
数据如下:
2014010114 2014010216 2014010317 2014010410 2014010506 2012010609 2012010732 2012010812 2012010919 2012011023 2001010116 2001010212 2001010310 2001010411 2001010529 2013010619 2013010722 2013010812 2013010929 2013011023 2008010105 2008010216 2008010337 2008010414 2008010516 2007010619 2007010712 2007010812 2007010999 2007011023 2010010114 2010010216 2010010317 2010010410 2010010506 2015010649 2015010722 2015010812 2015010999 2015011023
题目一:
解题思路:
通过年份进行分组求最大气温即可
使用hive解决步骤:
1,创建一个外部表:temperature
语法:
create external table if not exists temperature(line string); 加载数据 load data local inpath "/test_datas/temperature.txt" into table temperature; 数据查询: select substr(line,1,4),max(cast(substr(line,9,2) as int)) from temperature group by substr(line,1,4); 可得结果: 2001 29 2007 99 2008 37 2010 17 2012 32 2013 29 2014 17 2015 99
第二题:
解题思路:由于通过分组查询并且具体日期并不在分组字段中,hive提供了一种可以直接查出函数 collect_set()
create table step_2 as select substr(line,1,4) date_time,collect_set(line)[0] line ,max(cast(substr(line,9,2) as int)) max_tmp from temperature group by substr(line,1,4);
可得到一下结果数据
2001 2001010116 29 2007 2007010619 99 2008 2008010105 37 2010 2010010114 17 2012 2012010609 32 2013 2013010619 29 2014 2014010114 17 2015 2015010649 99
2,1 题目可以有两种理解,第一种展示具体日期即可,较简单 ===》
select date_time,substr(line,4,8) dates max_tmp from step_2;
2.2 另一种理解为要求得日期是当年的第几天
可以采用自定义函数来实现
1,java自定义函数 继承 UDF
2,重写evaluate
3,导出jar包
4,上传到linux
5,add jar jar路径 //不要加引号
add jar /root/lower.jar
6,关联到hive中
create temporary function 自定义函数名 as '包的函数名' //包的函数名:全路径名
具体代码如下:
public class DateToDay extends UDF{
/* public static void main(String[] args) throws ParseException {
String string = "20191231";
System.out.println(evaluate(string));
}*/
public static String evaluate(String s) throws ParseException {
LocalDate date = LocalDate.of(Integer.parseInt(s.substring(0,4)), Integer.parseInt(s.substring(4,6)), Integer.parseInt(s.substring(6,8)));
int dayOfYear = date.getDayOfYear();
return dayOfYear + "";
}
}
8 添加完之后可以测试
list jars
或者 show functions;
然后即可求得最终结果
select date_time ,dateToDay(substr(line,1,8)),max_tmp from step_2; 结果如下: 2001 1 29 2007 6 99 2008 1 37 2010 1 17 2012 6 32 2013 6 29 2014 1 17 2015 6 99

浙公网安备 33010602011771号