首页 > 解决方案 > Hive SQL:获取一定范围内每年对应的最大值列表

问题描述

我有一个这样的数据集:

ticker | value | year
  A       1      2008
  A       2      2008
  A       5      2010
  A       6      2006
  B       7      2010

我正在尝试编写一个 Hive SQL,它在股票代码上返回一个 GROUP BY,其中值是对应于特定范围内每年的最大值列表。在这种情况下,如果范围是 2008-2010,它会返回类似的东西(不太确定结果的结构实际上是什么样子,我希望你能理解我的意思):

A [(year: 2008, value: 2), (year: 2009, value: 0 (found no value for this year)), (year: 2010, value: 5)]
B [(year: 2008, value: 0), (year: 2009, value: 0), (year: 2010, value: 7)]

特别是我不明白如何要求 Hive 返回与数据集中某个值的范围相对应的值列表。如果你能帮忙,我会很高兴。

标签: sqlhiverange

解决方案


如果您只需要有效值,您可以使用 where between

    select  ticker, max(value), year
    from my_table 
    where year between 2008 and 2010 
    group by ticker, year

    or if need  all the year you could build the set using union  

   select  m.ticker, max(coalesce(m.value,0)), m.year
    from  (
        select 2008 year
        union
        select 2009 year
        union 
        select 2010 year
        ) t
    left join my_table m on t.year = m.year
    group by ticker, year

推荐阅读