在我的工作中,我发现了使用RANK() 替代(可能是最近的?https://cloud.google.com/bigquery/docs/reference/standard-sql/numbering_functions)替代编号函数ROW_NUMBER() 的潜在缺点。
with minimal_reproducible as (
select 'test@test.com' as user_email, 'Joe' as user_first_name, 'John' as user_last_name, 123456790 as time, 1 is_deleted
union all
select 'test@test.com', 'Joe', 'John', 123456789, 0
union all
select 'test2@test.com', 'Jill', 'John', 123456789, 0
)
select user_email, user_first_name, user_last_name, time, is_deleted from (
select *,
rank() over (partition by user_email order by time desc) as rank
from minimal_reproducible) inner_table
where rank = 1
接受的答案确实提供了所需的解决方案,除非在 order by 子句中的平局事件再次返回重复记录:
with minimal_reproducible as (
select 'test@test.com' as user_email, 'Joe' as user_first_name, 'John' as user_last_name, 123456789 as time, 1 is_deleted
union all
select 'test@test.com', 'Joe', 'John', 123456789, 0
union all
select 'test2@test.com', 'Jill', 'John', 123456789, 0
)
select user_email, user_first_name, user_last_name, time, is_deleted from (
select *,
rank() over (partition by user_email order by time desc) as rank
from minimal_reproducible) inner_table
where rank = 1;
因此,更好的解决方案是使用ROW_NUMBER() 代替RANK() 以确保(尽管是任意的)唯一的user_email 可能发生的情况:
with minimal_reproducible as (
select 'test@test.com' as user_email, 'Joe' as user_first_name, 'John' as user_last_name, 123456789 as time, 1 is_deleted
union all
select 'test@test.com', 'Joe', 'John', 123456789, 0
union all
select 'test2@test.com', 'Jill', 'John', 123456789, 0
)
select user_email, user_first_name, user_last_name, time, is_deleted from (
select *,
row_number() over (partition by user_email order by time desc) as row_number
from minimal_reproducible) inner_table
where row_number = 1;
我希望这对任何使用这种方法对表进行重复数据删除的人有所帮助。