【问题标题】:De-duplicating rows in a table with respect to certain columns and retaining the corresponding values in the other columns in HIVE针对某些列对表中的行进行重复数据删除,并在 HIVE 中的其他列中保留相应的值
【发布时间】:2015-12-09 22:46:00
【问题描述】:

我需要使用具有 7 列的现有表在 HIVE 中创建一个临时表。我只想删除前三列的重复项,并在其他 4 列中保留相应的值。我不在乎仅使用前三行进行重复数据删除时实际删除了哪一行。

【问题讨论】:

  • 重要的是要注意,重复只发生在某些列而不是所有列。也就是说,整行不会在表格中的任何地方重复。

标签: hive


【解决方案1】:

如果您不考虑订购,您可以使用以下内容

create table table2 as 
select col1, col2, col3, 
      ,split(agg_col,"|")[0] as col4
      ,split(agg_col,"|")[1] as col5
      ,split(agg_col,"|")[2] as col6
      ,split(agg_col,"|")[3] as col7
from (Select col1, col2, col3,
             max(concat(cast(col4 as string),"|", 
                        cast(col5 as string),"|",
                        cast(col6 as string),"|",
                        cast(col7 as string))) as agg_col
from table1
group by col1,col2,col3 ) A;

下面是另一种方法,它可以很好地控制排序但比上面的方法慢

create table table2 as 
select col1, col2, col3,max(col4), max(col5), max(col6), max(col7)
from (Select col1, col2, col3,col4, col5, col6, col7,
             rank() over ( partition by col1, col2, col3 
                           order by col4 desc, col5 desc, col6 desc, col7 desc ) as col_rank
from table1 ) A
where A.col_rank = 1
GROUP BY col1, col2, col3;

rank() over(..) 如果按列的顺序都相等,则函数返回多个列,其排名为 '1'。在我们的例子中,如果有 2 列的所有 7 列具有完全相同的值,那么当我们使用 filter as col_rank =1 时就会出现重复。可以使用上面查询中所写的 max 和 group by 子句来消除这些重复项。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多