google-cloud-platform - Bigquery 中数组元素的总和
问题描述
我必须从表中计算出正数和(负+空或空值)的总数,基本上是 2 个值。我有以下查询来列出负值、空值和正值..但我想要整个计数。请协助。
SELECT
ARRAY(
SELECT count(value),
FROM UNNEST(event_data_results) where REGEXP_CONTAINS(name, r'data.result.result') and ((REGEXP_CONTAINS(value, r'^-?\d+$') and SAFE_CAST(value AS INT64) <= 0 ))) AS negative_attributes,
ARRAY(
SELECT count(value) as neg_val,
FROM UNNEST(event_data_results) where value = 'null' or value='' ) AS null_attributes,
ARRAY(
SELECT count(value),
FROM UNNEST(event_data_results) where REGEXP_CONTAINS(name, r'data.result.result') and (REGEXP_CONTAINS(value, r'^-?\d+$') and SAFE_CAST(value AS INT64) > 0 )) AS positive_attributes
FROM `table` where EXISTS (SELECT 1 FROM UNNEST(event_keys) as keys , UNNEST(event_data_results) as results WHERE keys.value = "attribute")
event_keys,event_data_results , data_metrics 都是可重复的结构
结果应该是正数:4 负数+空数:4
解决方案
以下是 BigQuery 标准 SQL
#standardSQL
SELECT
COUNTIF(result.value > 0) positive_attributes,
COUNTIF(result.value < 0) negative_attributes,
COUNTIF(IFNULL(result.value, 0) = 0) null_or_zero_attributes
FROM `project.dataset.table`,
UNNEST(event_data_results) AS result
WHERE EXISTS (
SELECT 1
FROM UNNEST(event_keys) AS key
WHERE key.value = "attribute"
)
您可以在此处添加您需要的任何条件
此外,如果result.value
是一个字符串 - 你可以SAFE_CAST(result.value AS INT64)
像你已经这样做的那样使用,所以我没有关注你案例的这方面
推荐阅读
- android - 有没有办法禁用特定软件包的使用?
- laravel - 如何在十月 Cms 静态中获取模型的表名?
- entity-framework - 在 EF Core 中使用 IsolationLevel 开始事务
- tensorflow - TensorBoard 无法正确加载
- xamarin.forms - 如何修复 AppCenter 构建错误 NETSDK1004
- angular - 过滤 Observable 数组以返回一个结果
- vue.js - 如何使用 Nuxt 正确导入 CSS 模块?
- java - 在字符串中,将具有某些属性的每个 HTML 元素添加到具有任意属性的任意值的新任意元素中
- typescript - 如何在两个类之间共享 TypeScript 函数定义?
- c++ - 内存对齐和虚拟地址空间