SQL Bigquery:将特定组的选择限制为 10

SQL Bigquery : Limiting the selection from a particular group to 10

下面是示例table

目前 table 每个 ID 的条目数没有限制。

我的要求是,先把ID按照rand的升序排序。然后只取前两行 ['ID' 和 'companies'.]

CREATE TABLE table_name (
    ID int,
    companies varchar(255),
    rand float(2)
);

INSERT INTO table_name VALUES (1, 'a', 0.2);
INSERT INTO table_name VALUES (1, 'b', 0.6);
INSERT INTO table_name VALUES (2, 'a', 0.4);
INSERT INTO table_name VALUES (2, 'b', 0.5);
INSERT INTO table_name VALUES (2, 'c', 0.3);
INSERT INTO table_name VALUES (3, 'a', 0.6);
INSERT INTO table_name VALUES (3, 'b', 0.7);
INSERT INTO table_name VALUES (3, 'c', 0.4);
INSERT INTO table_name VALUES (3, 'd', 0.2);

即对于最终的 table,每个 ID 最多只能包含 2 行。 (不需要包含 rand 列)

你要row_number()吗?

select * except(rn)
from (
    select t.*, row_number() over(partition by id order by rand) rn
    from table_name t
) t
where rn <= 2

这为每个 id 选择最多两个记录,它们具有最小的 rand;您可以根据您的实际排序标准安排 row_number()order by 子句。

下面是 BigQuery 标准 SQL

#standardSQL
SELECT rec.* FROM (
  SELECT ARRAY_AGG(STRUCT(id, companies) ORDER BY rand LIMIT 2) arr 
  FROM `project.dataset.table` t
  GROUP BY id
), UNNEST(arr) rec   

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

Row id  companies    
1   1   a    
2   1   b    
3   2   c    
4   2   a    
5   3   d    
6   3   c