【问题标题】:Rating rows by conditions按条件对行进行评级
【发布时间】:2021-09-13 09:40:12
【问题描述】:

The existing Dataset

大家好, 现有数据集:

Student_id  Book_id class_id    timestamp
1101        NV5602  12          null
1101        NV5401  31          11/09/2021 16:50
1101        NV5401  12          null

我的 book_id 首先由 2 个字母组成,然后是数字。我想为每个 Student_id 选择最高的 book_id 编号(NV5602 - 在上面的示例中)。

如果有 2 个 book_id 具有相同的编号(在我们的示例中:NV5401)对于相同的 student_id,则将时间戳记为 1 的行评分为 1,将另一个为 null 的行评分为 2。

如果 book_id 和 student_id 的所有时间戳都为空 - 将其评为 1

输出应该是这样的:

Student_id  Book_id class_id    timestamp   row_number
1101        NV5602  12          null        1
1101        NV5401  31  11/09/2021 16:50    1
1101        NV5401  12          null        2

The desired output

【问题讨论】:

  • 能否请您以文本形式发布数据,而不是图片。请阅读 hiw 以询问有关 [hive] 的问题:stackoverflow.com/tags/hive/info
  • 删除了 [hql] 标签。它用于 hybernate,而不是 Apache Hive,请改用 [hiveql]
  • 感谢告知,我已经改了,希望现在可以了
  • 好多了!如果所有行都有时间戳并且存在具有相同 book_id 的行怎么办?
  • 这种情况不可能发生,因为每个 book_id 都有时间(书已借)或还没有借(空)。所以每个 book_id 只有 2 个选项

标签: hive hiveql


【解决方案1】:

使用 row_number。演示:

with mydata as (
select 1101 Student_id, 'NV5602' Book_id,  12 class_id,  null timestamp_ union all
select 1101, 'NV5401',  31,  '11/09/2021 16:50' union all
select 1101, 'NV5401',  12,  null
)

select Student_id,  Book_id, class_id, timestamp_, 
       row_number() over(partition by student_id, case when timestamp_ is null then 1 else 0 end  order by regexp_extract(Book_id,'[A-Z]+(\\d+)$',1) desc) as row_number
from mydata

结果:

student_id  book_id class_id    timestamp_         row_number
1101        NV5401  31          11/09/2021 16:50    1
1101        NV5602  12          NULL                1
1101        NV5401  12          NULL                2

【讨论】:

  • 谢谢,当我运行它时,它会在 row_number 处给出所有 1
猜你喜欢
  • 2018-05-27
  • 2011-07-17
  • 2017-07-28
  • 2013-01-08
  • 2012-01-22
  • 2020-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多