【问题标题】:Creating a view from another table从另一个表创建视图
【发布时间】:2018-08-03 01:05:52
【问题描述】:

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

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

尝试从上述视图中获取输出,如图所示(图 2),即将这些列中的值分组:

【问题讨论】:

  • 到目前为止你有什么尝试?
  • 个别查询工作,例如:select w1,count(*) from 'table_name' group by w1 等等。但我不确定如何组合查询以获得此输出

标签: sql google-bigquery views


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-26
    • 2020-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多