在缺少值的组中选择唯一行

qmb5sa22  于 2021-06-26  发布在  Hive
关注(0)|答案(3)|浏览(317)

我有一个包含两列的表,其中一列的值可能会丢失。第一列是id,第二列是value。我想为唯一id选择行,这样如果有多个行具有相同的id,但其中一些缺少值,则返回其中一个具有现有值。如果id为的所有行都有空值,则返回其中任何一行。
换句话说,只要两行具有相同的id,它们就应该属于同一组。但在每个组中,如果有值,则返回具有值的值。
例如,输入表。

  1. +--------+---------+
  2. | ID | VALUE |
  3. +------------------+
  4. | x | 1 |
  5. | x | 1 |
  6. | y | 2 |
  7. | y | |
  8. | z | |
  9. | z | |
  10. +------------------+

应返回:

  1. +------------+---------+
  2. | ID | VALUE |
  3. +------------+---------+
  4. | x | 1 |
  5. | y | 2 |
  6. | z | |
  7. +------------+---------+
a11xaf1n

a11xaf1n1#

根据你的描述,你可以用 max() :

  1. select id, max(value)
  2. from t
  3. group by id;

如果需要其他列,请使用 row_number() :

  1. select t.*
  2. from (select t.*,
  3. row_number() over (partition by id order by (case when value is not null then 1 else 0 end)) as seqnum
  4. from t
  5. ) t
  6. where seqnum = 1;
p5cysglq

p5cysglq2#

您可以轻松地将查询分为两个查询:

  1. A: 1- find unique row with DISTINCT on (ID,Value) which are not empty VALUE
  2. B: 2- find unique row with DISTINCT on ID which are empty in VALUE and ID not in(A(ID))

a u(b-a)

gopyfrb3

gopyfrb33#

您可以在hive/sql中使用distinct函数

  1. hive> select distinct id,value from <db_name>.<table_name>;

上面的查询将在id、value列中返回不同的值

  1. hive> select distinct * from <db_name>.<table_name>;

上面的语句用于基于所有列仅返回不同(不同)的值。

相关问题