如何从Hive表中获取记录,其中月=当前月份,其他月份=上个月(当前月份– 1)?

时间:2019-11-20 08:54:33

标签: hive bigdata

我遇到一种情况,我需要从Hive表中检索数据,其中month =当月。如果当前月份的数据不可用,我需要从上个月获取。我们如何在Hive查询中实现这种情况。

我的查询正确吗?

Select emp_name, emp_number,
case when emonth IS NULL then concat(year(current_date()),'-' ,month(current_date())-1) else emonth end
FROM db.emptable
where emonth =concat(year(current_date()),'-' ,month(current_date()))

我不确定上述查询,因为如果我在表CASE条件中没有当前月份记录,只需在 emonth列 中分配上个月。 但是,如果月份是当前月份,则我需要进行验证,否则获取前一个月的数据。

2 个答案:

答案 0 :(得分:0)

month(字符串日期)可用于从任何日期戳中获取月份。

因此您可以尝试:

选择emp_name,emp_number, 如果emonth为NULL则为month(add_months(current_date(),-1)) 还有一个月 结束 FROM db.emptable

答案 1 :(得分:0)

使用row_number过滤数据:

select  emonth, emp_name, emp_number
 from
(
select emonth, emp_name, emp_number,
       row_number() over (partition by emp_number order by case when emonth= substr(current_date(),1,7) then 1 else 2 end ) rn
  from db.emptable
where emonth >= substr(add_months(concat(substr(current_date(),1,7),'-01'),-1),1,7) --prev month
)s
where rn=1 -- If current month is absent, previous month rn=1

根据需要正确地在row_number中写入partition by子句。在我的答案中,将为每个emp_number计算row_number。

相关问题