【问题标题】:how to remove duplicated records depend on column not able to sort in hive如何删除重复记录取决于无法在配置单元中排序的列
【发布时间】:2022-01-16 04:14:15
【问题描述】:

我有:

表测试包含:

unique_id string , file_name string , mount bigint

日期样本:

uniqu_id , file_name             , mount 
1        , test.txt              , 15
1        , test_R_file.txt       , 50
3        , test_567.txt          , 30
3        , test_567_R_file.txt   , 100

我想做什么:

我需要查询插入覆盖我需要为每个重复的 uniqu_id 保留一条记录的表,并且该记录应该是具有(R 在文件名列中)的记录

问题:

测试表是 hive 中的外部表(这意味着它不支持更新和删除操作)所以我想插入覆盖以删除表中每个 uniqu_id 的重复记录(如果我有 2 条相同的 unique_id 记录只有记录在文件名记录中有 (R) 的文件应该保留),我想使用排名,但我没有列要排序的想法是知道我应该保留什么记录以及我应该保留什么记录删除我只有 file_name 列我应该检查它以防我有 2 条记录具有相同的 unique_id 以知道我应该保留哪些记录以及应该删除哪些记录

【问题讨论】:

    标签: sql hive hiveql ranking


    【解决方案1】:

    您可以按布尔表达式排序 R 是否存在于文件名中或不使用 CASE 表达式。您还可以在 CASE 中将 boolean 转换为 int 并向 CASE 添加更多条件以及添加更多 orderby 表达式,逗号分隔。您可以按布尔值排序,因为 True 大于 False。

    演示:

    with mytable as (--demo dataset, use your table instead of this CTE
    select 1 unique_id , 'test.txt' file_name , 15 mount union all
    select 1        , 'test_R_file.txt'       , 50 union all
    select 3        , 'test_567.txt'          , 30 union all
    select 3        , 'test_567_R_file.txt'   , 100
    )
    
    select unique_id, file_name, mount
    from 
    (
    select unique_id, file_name, mount, 
           row_number() over(partition by unique_id
                                 order by file_name rlike '_R_' desc --True is greater than False
                                          --order by something else if necessary
                            ) rn
           from mytable t
    ) s
    where rn=1
    

    结果:

    unique_id   file_name            mount
    1           test_R_file.txt      50
    3           test_567_R_file.txt  100
    

    如果每个 unique_id 可能有多个带有 R 的记录并且您希望保留所有记录,请使用 rank 而不是 row_number。 Rank 将为具有 R 的所有记录分配 1,row_number 将为每个 unique_id 的唯一此类记录分配 1。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-18
      • 2011-08-07
      • 1970-01-01
      • 1970-01-01
      • 2018-03-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多