Sql 为列的每个值选择最小值
我有一张这样的桌子:Sql 为列的每个值选择最小值,sql,google-bigquery,greatest-n-per-group,Sql,Google Bigquery,Greatest N Per Group,我有一张这样的桌子: col1 col2 num a <string1> 5 a <string2> 10 a <string3> 0 a <string4> 7 b <string1> 6 b <string2> 3 b <string3>
col1 col2 num
a <string1> 5
a <string2> 10
a <string3> 0
a <string4> 7
b <string1> 6
b <string2> 3
b <string3> 20
b <string4> 1
我想为col1或col2的每个值选择minnum,因此期望的输出是:
col1 col2 num
a <string3> 0
b <string4> 1
我怎样才能做到这一点?我正试图在BigQuery中实现这一点。如果您以标记的方式运行Postgres,您可以在以下位置使用distinct: 在问题中提到的BigQuery中,可以使用数组执行此操作:
select array_agg(t order by num limit 1)[offset(0)].*
from mytable t
group by col1
下面是BigQuery标准SQL
#standardSQL
select as value array_agg(t order by num limit 1)[offset(0)]
from `project.dataset.table` t
group by col1
如果要应用于问题中的样本数据,如下例所示
#standardSQL
WITH `project.dataset.table` AS (
select 'a' col1, '<string1>' col2, 5 num union all
select 'a', '<string2>', 10 union all
select 'a', '<string3>', 0 union all
select 'a', '<string4>', 7 union all
select 'b', '<string1>', 6 union all
select 'b', '<string2>', 3 union all
select 'b', '<string3>', 20 union all
select 'b', '<string4>', 1
)
select as value array_agg(t order by num limit 1)[offset(0)]
from `project.dataset.table` t
group by col1
输出是
BigQuery还是Postgres?请根据问题的描述或其他方式调整标签…它的bigquery。我搞错了。对不起,我的错,谢谢你们!这确实奏效了。最后一件事,我添加了where num
#standardSQL
WITH `project.dataset.table` AS (
select 'a' col1, '<string1>' col2, 5 num union all
select 'a', '<string2>', 10 union all
select 'a', '<string3>', 0 union all
select 'a', '<string4>', 7 union all
select 'b', '<string1>', 6 union all
select 'b', '<string2>', 3 union all
select 'b', '<string3>', 20 union all
select 'b', '<string4>', 1
)
select as value array_agg(t order by num limit 1)[offset(0)]
from `project.dataset.table` t
group by col1