Sql 在数组中搜索值并返回值
我想在数组中搜索一个值,如果找不到该值,那么我想返回数组中的最大值 数据如下所示- (ID为数据类型字符串,Product_ID为数据类型整数) 因此,在本例中,我要搜索值“5432”。如果找到该值,则返回该值,否则返回最大值。所以,结果应该是这样的-Sql 在数组中搜索值并返回值,sql,google-bigquery,Sql,Google Bigquery,我想在数组中搜索一个值,如果找不到该值,那么我想返回数组中的最大值 数据如下所示- (ID为数据类型字符串,Product_ID为数据类型整数) 因此,在本例中,我要搜索值“5432”。如果找到该值,则返回该值,否则返回最大值。所以,结果应该是这样的- ID Product_id ABC123 5432 PQR567 5432 LMN789 9999 下面是BigQuery标准SQL #standardSQL SELECT ID,
ID Product_id
ABC123 5432
PQR567 5432
LMN789 9999
下面是BigQuery标准SQL
#standardSQL
SELECT ID,
( SELECT IF(COUNTIF(id = 5432) = 0, MAX(id), 5432)
FROM t.Product_id id
) AS Product_id
FROM `project.dataset.table` t
您可以使用问题中的样本数据测试、播放上述内容,如下例所示
#standardSQL
WITH `project.dataset.table` AS (
SELECT 'ABC123' ID, [1122,5432,6099] Product_id UNION ALL
SELECT 'PQR567', [5432,0793,1111] UNION ALL
SELECT 'LMN789', [1111,2222,9999]
)
SELECT ID,
( SELECT IF(COUNTIF(id = 5432) = 0, MAX(id), 5432)
FROM t.Product_id id
) AS Product_id
FROM `project.dataset.table` t
有输出
Row ID Product_id
1 ABC123 5432
2 PQR567 5432
3 LMN789 9999
另一个稍有不同的选项-仅引用一个搜索值(5432)
我想我会这样写:
select t.*,
(select coalesce(max(case when product_id = 5432 then product_id end),
max(product_id)
)
from unnest(t.product_ids) product_id
) as product_id
from t;
#standardSQL
SELECT ID,
( SELECT IFNULL(MAX(IF(id = 5432, id, NULL)), MAX(id))
FROM t.Product_id id
) AS Product_id
FROM `project.dataset.table` t
select t.*,
(select coalesce(max(case when product_id = 5432 then product_id end),
max(product_id)
)
from unnest(t.product_ids) product_id
) as product_id
from t;