如何创建汇总表

时间:2019-05-03 13:58:00

标签: sql google-bigquery

给定一个列出演员的动作的表(我隐藏了不相关的时间戳列),我们希望有一个汇总表,列出每个演员的行以及他的动作计数。 我们已经预定义了三种可能的操作

标准SQL或Google BigQuery语法


Actor   |   Action
_________________
Sam         shoot
Sam         shoot
Sam         heal
Sam         dead
Bob         shoot
Bob         shoot
Bob         shoot
Bob         dead

收件人


Actor   |  shoot  |  heal   | Dead
_____________________________________
Sam        2          1         1
Bob        3          0         1

1 个答案:

答案 0 :(得分:1)

如果知道所需的列,请使用countif()

select actor,
       countif(action = 'shoot') as shoot,
       countif(action = 'heal') as heal,
       countif(action = 'dead') as dead
from t
group by actor;

如果不这样做,那么您将面临挑战,因为SQL查询往往需要知道结果集中的列。一种解决方法是将值放在行而不是列中:

actor    action     count
 sam     shoot        2
 . . .

也就是说:

select actor, action, count(*)
from t
group by actor, action;

(这不包括0个计数,但是可以对此进行调整。)

或者使用JSON或数组存储每个操作的值。

相关问题