我想从另一个表创建一个视图。
当前视图具有以下内容(图像1):
尝试从上面的视图中获取输出,如图所示(图2),即对这些列中的值进行分组:
答案 0 :(得分:2)
一种方法是取消数据透视,然后重新聚合:
select w,
sum(case when i = 0 then 1 else 0 end) as w1,
sum(case when i = 1 then 1 else 0 end) as w2,
sum(case when i = 2 then 1 else 0 end) as w3,
sum(case when i = 3 then 1 else 0 end) as w4
from (select array[w1, w2, w3, w4] ws
from t
) t cross join
unnest(ws) w with offset i
group by w;
这是一个更完整的示例:
with t as (
select 1 as slno, '<5' as w1, '<5' as w2, '<5' as w3, '<5' as w4 union all
select 1 as slno, '<5' as w1, '5 to 10' as w2, '<5' as w3, '5 to 10' as w4
)
select w,
sum(case when i = 0 then 1 else 0 end) as w1,
sum(case when i = 1 then 1 else 0 end) as w2,
sum(case when i = 2 then 1 else 0 end) as w3,
sum(case when i = 3 then 1 else 0 end) as w4
from (select array[w1, w2, w3, w4] as ws
from t
) t cross join
unnest(ws) w with offset i
group by w;
答案 1 :(得分:1)
以下是用于BigQuery标准SQL
#standardSQL
SELECT bucket,
COUNTIF(col = 0) AS w1,
COUNTIF(col = 1) AS w2,
COUNTIF(col = 2) AS w3,
COUNTIF(col = 3) AS w4
FROM `project.dataset.your_table`,
UNNEST([w1, w2, w3, w4]) bucket WITH OFFSET col
GROUP BY bucket