Return最高计数记录

Return the highest count record

我正在处理的数据如下所示-

A_ID          B_ID           count
123           abcd          1000
123           aaaa          2000
123           aaaa          3000
456           null          50
456           bbbb          6000
456           cccc          450

我希望能够提取给定 A_id

中计数最高的 B_id

结果应该是这样的-

A_ID          B_ID        count
123           aaaa        3000
456           bbbb        6000

如何实现这个结果?

您可以在 BigQuery 中使用聚合:

select array_agg(t order by count desc limit 1)[ordinal(1)].*
from t
group by a_id;

一个选项是使用子查询进行过滤:

select t.*
from mytable t
where t.count = (select max(t1.count) from mytable t1 where t1.a_id = t.a_id)

您还可以使用 window 函数:

select t.* except(rn)
from (
    select t.*, rank() over(partition by a_id order by count desc) rn
    from mytable t
) t
where rn = 1

以下适用于 BigQuery 标准 SQL

#standardSQL
SELECT AS VALUE ARRAY_AGG(t ORDER BY count DESC LIMIT 1)[OFFSET(0)]
FROM `project.dataset.table` t
GROUP BY a_id   

如果应用于您问题中的示例数据 - 输出为

Row a_id    b_id    count    
1   123     aaaa    3000     
2   456     bbbb    6000