簡體   English   中英

使用 BigQuery SQL 計算同一 ID 的所有列值的模式

[英]Calculate mode of all column values for the same ID using BigQuery SQL

假設我有一個 Bigquery 表,其中包含idspeciesgenrelevel列。 在某些情況下,對於相同的idspeciesgenre ,我的表可能在多行中具有不同的level值。

最后,我希望每個id有 1 行,其level值作為該id原始表中存在的所有level值的mode

例子

#standardSQL
with `project.dataset.table` as (
  select '123' id, 'dog' species, 'suspense' genre, 3 level  union all 
  select '124', 'cat', 'love', 4 union all 
  select '123', 'dog', 'suspense', 5 union all
  select '123', 'dog', 'suspense', 5 
)
select *
from `project.dataset.table`

預期結果:相同的數據集,每個 id 一行。 例如。 在上面的示例中,對於id 123,級別將為5 (出現次數最多)

我怎么能做到這一點?

[更新] 以上數據只是一個例子。 我的實際數據集中有 2000 萬行,超過 4 列。

嘗試這個:

with `project.dataset.table` as (
  select '123' id, 'dog' species, 'suspense' genre, 3 level  union all 
  select '124', 'cat', 'love', 4 union all 
  select '123', 'dog', 'suspense', 5 union all
  select '123', 'dog', 'suspense', 5 
)
select id, array_agg(level order by cnt desc limit 1)[offset(0)] as mode
from (
  select id, level, count(level) as cnt
  from `project.dataset.table`
  group by id, level
)
group by id

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM