sql - 如何创建汇总表
问题描述
给定一个列出演员动作的表格(我隐藏了不相关的时间戳列),我们希望有一个汇总表,列出每个演员的一行以及他所做的每个动作的计数。我们已经预定义了三个可能的动作
标准 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
解决方案
如果您知道所需的列,请使用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 或数组来存储每个操作的值。