sql:给定日期的最大可用日期

7cjasjjr  于 2021-05-27  发布在  Hadoop
关注(0)|答案(5)|浏览(427)

我想计算一下 cash_date 列,如果为空,则应填充可用的最新日期。
sql脚本:

select 
       calendar_day
       ,cash_date
from dates_manager
where year(calendar_day)=2019
      and month(calendar_day)=11
group by 
        calendar_day
        ,cash_date


预期

w1e3prcc

w1e3prcc1#

你可以用 max() 作为窗口函数:

select dm.calendar_day,
       coalesce(dm.cash_date, max(dm.cash_date) over (order by dm.calendar_day)) as cash_date
from dates_manager dm
where year(calendar_day) = 2019 and
      month(calendar_day) = 11
group by dm.calendar_day, dm.cash_date;
yb3bgrhw

yb3bgrhw2#

你在找什么 LAST_VALUE ,记录如下:http://dwgeek.com/hadoop-hive-analytic-functions-examples.html/ 在这里:https://docs.cloudera.com/documentation/enterprise/5-11-x/topics/impala_analytic_functions.html

select 
  calendar_day,
  last_value(cash_date ignore nulls) over (order by calendar_day) as cash_day
from dates_manager
where year(calendar_day) = 2019 and month(calendar_day) = 11
order by calendar_day;

我添加了 ORDER BY 缺少您的查询。我移除了 GROUP BY 子句,因为查询不包含聚合函数。如果表中每天可能有多个条目,您必须相应地调整我的查询。

yb3bgrhw

yb3bgrhw3#

使用分析函数计算最大日期,如果为空则替换:

select 
     calendar_day,
     nvl(cash_date, max_cash_date) as cash_date 
from
(
select 
       calendar_day
       ,cash_date
       ,max(cash_date) over(partition by year(calendar_day), month(calendar_day) order by calendar_day rows between unbounded preceding and current row) as max_cash_date
from dates_manager
where year(calendar_day)=2019
      and month(calendar_day)=11
)s
group by 
        calendar_day
        ,nvl(cash_date, max_cash_date)
35g0bw71

35g0bw714#

你为什么不试试这个?
它只会得到那些数据 cash_data 不为空。

select 
calendar_day
,cash_date
from dates_manager
where year(calendar_day)=2019
and month(calendar_day)=11 and cash_date IS NOT NULL
group by 
calendar_day
,cash_date

根据你的问题,
你的问题很好,
现在当你得到结果时,
只要把它作为你的代码,在那里你就可以处理并用你得到的最大日期替换空值。
或者你可以尝试下面的代码来得到结果

select 
calendar_day
,max(cash_date)
from dates_manager
where year(calendar_day)=2019
and month(calendar_day)=11 and cash_date IS NOT NULL
group by 
calendar_day
,cash_date
kjthegm6

kjthegm65#

作为参考,我成功地解决了我的问题:max(cash\u date)over(order by calendar\u day asc rows unbounded previous)

相关问题