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

Hive 如何从配置单元表中获取记录,其中月份=当前月份,其他月份=上个月(当前月份–1)?,hive,hiveql,Hive,Hiveql,我需要从配置单元表中检索数据,其中月份=当前月份。如果当前月份的数据不可用,我需要从上个月获取。如何在配置单元查询中实现这种情况 我的问题对吗 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(cu

我需要从配置单元表中检索数据,其中月份=当前月份。如果当前月份的数据不可用,我需要从上个月获取。如何在配置单元查询中实现这种情况

我的问题对吗

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 condition中没有当前月份记录,只需在emonth列中分配上一个月即可。
但是如果月份是当前月份,则需要进行验证,否则需要获取上一个月的数据。

可以使用monthstring date从任何日期戳获取月份

因此,您可以尝试:

选择emp_名称、emp_编号, 当emonth为NULL时,则monthadd_months当前日期,-1 埃蒙斯酒店 终止
从db.emptable

使用行号筛选数据:

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

在行_编号中写入partitionby子句,因为您需要正确计算它。在我的回答中,将为每个emp_编号计算行编号

嗨,Pawan,你的意思是我们不需要处理where条款?其实不太清楚。我让它变得简单。我需要获取emp数据,其中月份是当前月份,如果当前月份没有可用的数据,我需要从上个月获取。