使用最新条目

时间:2016-07-19 21:36:53

标签: database group-by hive

我正在尝试编写一个查询来获取唯一的交易值,包括销售价值和最新发布日期。

这是我的问题:

select transaction, sales, max(sale_date) from xyz_table where report_date = 20160718 group by transaction, sales;

这是我得到的结果: 这是样本数据:

|transaction     |     sales| sale_date| report_date|
|1397115220084030|  0.000144|   20160714|20160718|
|13971230534538500| 0       |   20160716|20160718|    
|13973937437448300| 0.000001|   20160716|20160718|    
|13976744119997000| 0.008563|   20160714|20160718|    
|13976744119997000| 0.002392|   20160715|20160718|

我想要的是与最新销售日期的独特交易: 这是必需的数据:

|transaction     |     sales| sale_date| report_date|
|1397115220084030|  0.000144|   20160714|20160718|
|13971230534538500| 0       |   20160716|20160718|    
|13973937437448300| 0.000001|   20160716|20160718|    
|13976744119997000| 0.002392|   20160715|20160718|

我试图做最大的销售但是仍然没有给出正确的结果:

select transaction, Max(sales), max(sale_date) from xyz_table where report_date = 20160718 group by transaction;

错误的结果: 这是必需的数据:

|transaction     |     sales| sale_date| report_date|
|1397115220084030|  0.000144|   20160714|20160718|
|13971230534538500| 0       |   20160716|20160718|    
|13973937437448300| 0.000001|   20160716|20160718|    
|13976744119997000| 0.008563|   20160715|20160718|

请有人帮助我。

由于

1 个答案:

答案 0 :(得分:1)

在Hive中,您将使用窗口函数:

select t.*
from (select t.*, 
             row_number() over (partition by transaction order by sale_date desc) as seqnum
      from transactions t
     ) t
where seqnum = 1;

MySQL查询会有很大不同,因为它不支持这种ANSI标准功能。

相关问题