从另一个表创建视图
Posted
技术标签:
【中文标题】从另一个表创建视图【英文标题】:Creating a view from another table 【发布时间】:2018-08-03 01:05:52 【问题描述】:我想从另一个表创建一个视图..
当前视图具有以下内容(图 1):
尝试从上述视图中获取输出,如图所示(图 2),即将这些列中的值分组:
【问题讨论】:
到目前为止你有什么尝试? 个别查询工作,例如:select w1,count(*) from 'table_name' group by w1 等等。但我不确定如何组合查询以获得此输出 【参考方案1】:一种方法是取消透视数据,然后重新聚合:
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;
【讨论】:
这是我给出的一个例子,只有 5 行。但是,实际表有大约 1k 行。是否有另一种方法来总结大量计数的值? @user10173721 。 . .行数在此无关紧要。汇总所有行。【参考方案2】:以下是 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
【讨论】:
以上是关于从另一个表创建视图的主要内容,如果未能解决你的问题,请参考以下文章