【问题标题】:How can i join a table with another, then count not empty columns and group them by two other fields?如何将一个表与另一个表连接,然后计算非空列并将它们按另外两个字段分组?
【发布时间】:2021-07-07 14:53:27
【问题描述】:

(我在添加表格时遇到了一些问题,因为它们被视为代码。已将标签添加为代码以包含它)

我有一个包含许多列的表(示例中只有几个)

month col1 col2 col3 col4 col5
2021.06 87 987 987 87
2021.06 86 09 65
2021.06 09 65
2021.06 09
2021.05 85 09 65
2021.05 85 09
2021.05 87 09

我还有第二个表,其中包含与上表中的 id 号相关的附加信息:

id branch info1 info2
85 branch1 test4 test5
86 branch1 test3
87 branch2 test2
987 test1
09 branch3 test1
65 branch1 test1

我需要找到一种简单的加入信息的方法,计算非空列的数量并按月份和分支分组。结果应该是这样的

month branch col1 col2 col3 col4 col5
2021.05 branch1 2 0 0 0 1
2021.05 branch2 1 0 0 0 0
2021.05 branch3 0 0 0 3 0
2021.06 branch1 0 1 0 0 2
2021.06 branch2 0 1 0 0 1
2021.06 branch3 0 0 0 3 0
2021.06 0 0 1 1 0

我已尝试使用 join 和 union all,但查询变得非常大。

【问题讨论】:

  • 你忘了显示输入数据 :o)
  • 由于某种原因无法添加表格。错误说它是代码,但不是。现在将其添加为代码
  • 现在已正确添加。发现我需要在表格中的空单元格中添加一个空格,以便它们不被视为代码:-)

标签: join count google-bigquery union-all


【解决方案1】:

考虑以下方法

select * from (
  select month, branch, id, col
  from table1 
  unpivot (id for col in (col1,col2,col3,col4,col5))
  left join table2 using(id)
)
pivot (count(id) for col in ('col1','col2','col3','col4','col5'))
# order by month, branch nulls last     

如果应用于您问题中的样本数据 - 输出是

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-10
    • 1970-01-01
    • 1970-01-01
    • 2011-03-13
    • 1970-01-01
    • 2023-03-19
    • 2011-12-27
    相关资源
    最近更新 更多