查找Hive中一年的最大发生次数

qmb5sa22  于 2021-06-27  发布在  Hive
关注(0)|答案(1)|浏览(325)

这里有一些信用卡记录,我需要找出一年中有最多的信用卡到期日。因为日期不在 YYYY/MM/DD 因此,在模式中,我将日期定义为“string”类型

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
hs1ihplo

hs1ihplo1#

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

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
);

相关问题