从另一个 table 创建视图

Creating a view from another table

我想从另一个 table 创建一个视图..

当前视图有以下内容(图片 1):

尝试从上面的视图中获取输出(图 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;

以下适用于 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