![](/img/trans.png)
[英]SQL- Add up all the values in a resulting column and calculate the percentage using another column in the same query
[英]Calculate mode of all column values for the same ID using BigQuery SQL
假設我有一個 Bigquery 表,其中包含id
、 species
、 genre
和level
列。 在某些情況下,對於相同的id
、 species
和genre
,我的表可能在多行中具有不同的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.