我想在标准SQL中透视和计数以下数据(将Google附加OWOX BI与Big Query结合使用):
,以便它在标准sql中输出如下:
所以我想选择itemsku并根据“原因”进行透视。
无法解决这个问题,谢谢!!!
答案 0 :(得分:2)
以下是用于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
答案 1 :(得分:0)
您可以使用条件聚合:
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
。