我如何在标准 SQL 中进行 PIVOT 和 COUNT

How can I PIVOT and COUNT in Standard SQL

我想在标准 SQL 中转换和计算以下数据(使用 Google Add-On OWOX BI with Big Query):

以便它以标准 sql 输出,如下所示:

所以我想 select itemsku 和枢轴基于 "Reason."

想不通,谢谢!!!

您可以使用条件聚合:

select itemsku,
       sum(case when reason = 'BIG' then 1 end) as big,
       sum(case when reason = 'SMALL' then 1 end) as small,
       sum(case when reason = 'NONE' then 1 end) as none
from t
group by itemsku;

如果您想要 0 而不是 NULL,请将 else 0 添加到大小写表达式中。

以下适用于 BigQuery 标准 SQL

#standardSQL
SELECT itemsku,
       COUNTIF(reason = 'BIG') AS big,
       COUNTIF(reason = 'NONE') AS none,
       COUNTIF(reason = 'SMALL') AS small
FROM `project.dataset.table`
GROUP BY itemsku

您可以使用您问题中的虚拟数据进行测试,如下所示

#standardSQL
WITH `project.dataset.table` AS (
  SELECT 1010101 itemsku, 'BIG' reason UNION ALL
  SELECT 1010101, 'BIG' UNION ALL
  SELECT 13333, 'NONE' UNION ALL
  SELECT 13333, 'NONE' UNION ALL
  SELECT 14444, 'NONE' UNION ALL
  SELECT 14444, 'NONE' UNION ALL
  SELECT 14444, 'SMALL' 
)
SELECT itemsku,
       COUNTIF(reason = 'BIG') AS big,
       COUNTIF(reason = 'NONE') AS none,
       COUNTIF(reason = 'SMALL') AS small
FROM `project.dataset.table`
GROUP BY itemsku
-- ORDER BY itemsku     

结果为

Row     itemsku     big     none    small    
1       13333       0       2       0    
2       14444       0       2       1    
3       1010101     2       0       0