我怎样才能将 table 与另一个加入,然后计算不为空的列并将它们按其他两个字段分组?

How can i join a table with another, then count not empty columns and group them by two other fields?

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

我有一个 table 有很多列(例如只有几个)

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

我还有第二个 table,其中包含与上述 ID 号码相关的附加信息 table:

id 分支机构 信息1 信息2
85 分支 1 测试4 测试5
86 分支 1 测试3
87 分支 2 测试2
987 测试1
09 分支 3 测试1
65 分支 1 测试1

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

分支机构 col1 col2 col3 col4 col5
2021.05 分支 1 2 0 0 0 1
2021.05 分支 2 1 0 0 0 0
2021.05 分支 3 0 0 0 3 0
2021.06 分支 1 0 1 0 0 2
2021.06 分支 2 0 1 0 0 1
2021.06 分支 3 0 0 0 3 0
2021.06 0 0 1 1 0

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

考虑以下方法

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     

如果应用于您问题中的示例数据 - 输出为