获取具有最新条目的唯一值查询

x6yk4ghg  于 2021-06-28  发布在  Hive
关注(0)|答案(1)|浏览(306)

我正在尝试编写一个查询来获取唯一的事务值,其中包含sale值和最近发生的日期。
我的问题是:

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|

有人能帮帮我吗。
谢谢

t40tm48m

t40tm48m1#

在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标准功能。

相关问题