对 BigQuery 中多列的数字求和

Ben*_*n P 5 sql google-bigquery

我有一个查询返回许多列,这些列要么是 1 要么是 0,具体取决于用户与网站的许多点的交互,我的数据如下所示:

UserID   Variable_1   Variable_2   Variable_3   Variable_4   Variable_5
User 1        1           0             1            0           0
User 2        0           0             1            0           0
User 3        0           0             0            0           1
User 4        0           1             1            1           1
User 5        1           0             0            0           1
Run Code Online (Sandbox Code Playgroud)

每个变量都用它自己的代码行定义,例如: MAX(IF(LOWER(hits_product.productbrand) LIKE "Variable_1",1,0)) AS Variable_1,

我想要一列汇总每个用户的所有行。看起来像这样:

UserID   Total     Variable_1   Variable_2   Variable_3   Variable_4   Variable_5
User 1     2             1           0             1            0           0
User 2     3             1           1             1            0           0
User 3     0             0           0             0            0           0
User 4     5             1           1             1            1           1
User 5     3             1           0             1            0           1
Run Code Online (Sandbox Code Playgroud)

实现这一目标的最优雅的方法是什么?

Mik*_*ant 7

即使对于OP的特殊情况,简单的 COUNT(DISTINCT) 就足够了 - 我仍然想回答原始问题:如何将所有数字列汇总为一个总计,而不依赖于这些列的数量和名称

以下是 BigQuery 标准 SQL

#standardSQL
SELECT 
  UserID,   
  ( SELECT SUM(CAST(value AS INT64)) 
    FROM UNNEST(REGEXP_EXTRACT_ALL(TO_JSON_STRING(t), r':(\d+),?')) value
  ) Total,
  * EXCEPT(UserID)
FROM t
Run Code Online (Sandbox Code Playgroud)

这可以使用问题中的虚拟数据进行测试/播放

#standardSQL
WITH t AS (
  SELECT 'User 1' UserID, 1 Variable_1, 0 Variable_2, 1 Variable_3, 0 Variable_4, 0 Variable_5 UNION ALL
  SELECT 'User 2', 1, 1, 1, 0, 0 UNION ALL
  SELECT 'User 3', 0, 0, 0, 0, 0 UNION ALL
  SELECT 'User 4', 1, 1, 1, 1, 1 UNION ALL
  SELECT 'User 5', 1, 0, 1, 0, 1 
)
SELECT 
  UserID,   
  ( SELECT SUM(CAST(value AS INT64)) 
    FROM UNNEST(REGEXP_EXTRACT_ALL(TO_JSON_STRING(t), r':(\d+),?')) value
  ) Total,
  * EXCEPT(UserID)
FROM t
ORDER BY UserID   
Run Code Online (Sandbox Code Playgroud)

结果是

Row UserID      Total   Variable_1  Variable_2  Variable_3  Variable_4  Variable_5   
1   User 1      2       1           0           1           0           0    
2   User 2      3       1           1           1           0           0    
3   User 3      0       0           0           0           0           0    
4   User 4      5       1           1           1           1           1    
5   User 5      3       1           0           1           0           1    
Run Code Online (Sandbox Code Playgroud)


Gor*_*off 3

一个简单的方法是使用子查询或 CTE:

select t.*, (v1 + v2 + v3 . . . ) as total
from (<your query here>
     ) t;
Run Code Online (Sandbox Code Playgroud)

不知道数据是什么样的,这很可能count(distinct hits_product.productbrand)也能达到目的。