首页 > 解决方案 > 在 Hive 中查找一年的最大出现次数

问题描述

这是一些信用卡记录,我需要找到卡到期日期最多的年份。由于日期不是YYYY/MM/DD格式,所以在模式中我将日期定义为“字符串”类型

Card Type Full Name,Card Holder's Name,Issue Date,Expiry Date,Card PIN

Discover,Brenda D Peterson,01/2017,01/2022,1998
Diners Club International,Dawn U Reese,12/2015,12/2013,3915 
Diners Club International,Helen P Perry,02/2007,02/2020,2319
American Express,Christine E Kim,08/2011,08/2013,9017

标签: hivehiveql

解决方案


此查询将为您提供记录数最多的年份。

select 
   substr(expiry_date, instr(expiry_date, '/')+1) as expiry_year,
   count(*) as cnt
from customers
group by substr(expiry_date, instr(expiry_date, '/')+1)
order by cnt desc
limit 1;

在这种情况下,您可以使用以下查询,有可能超过 1 年有相同数量的卡在那一年到期

select 
   substr(expiry_date, instr(expiry_date, '/')+1) as expiry_year
from customers
having count(*) = (
   select max(cnt) from (
      select 
         substr(expiry_date, instr(expiry_date, '/')+1) as expiry_year,
         count(*) as cnt
      from customers
         group by substr(expiry_date, instr(expiry_date, '/')+1)
   )t
);

推荐阅读