从 BigQuery 中的加权边列表构建邻接矩阵

Build adjacency matrix from list of weighted edges in BigQuery

相关问题: How to create dummy variable columns for thousands of categories in Google BigQuery

我有一个 table 加权边列表,它是一个用户项目评级列表,它看起来像这样:

| userId | itemId | rating
| 001    | 001    | 5.0
| 001    | 002    | 4.0
| 002    | 001    | 4.5
| 002    | 002    | 3.0

我想将这个加权边列表转换成邻接矩阵:

| userId | item001 | item002
| 001    | 5.0     | 4.0
| 002    | 4.5     | 3.0

根据this post,我们可以分两步进行,第一步是提取矩阵条目的值生成查询,第二步是运行查询是从第一步生成。

但我的问题是如何提取评级值并在IF()语句中使用评级值?我的直觉是在 IF() 语句中放置一个嵌套查询,例如:

IF(itemId = blah, 
                 (select rating 
                  from mytable 
                  where 
                    userId = blahblah 
                    and itemId = blah), 
                 0)

但是这个查询看起来太昂贵了,谁能给我一个例子吗?

谢谢

除非我遗漏了什么 - 它与您引用的 post 非常相似

Step 1 - generate query

SELECT 'SELECT userID, ' + 
   GROUP_CONCAT_UNQUOTED(
    'SUM(IF(itemId = "' + STRING(itemId) + '", rating, 0)) AS item' + STRING(itemId)
   ) 
   + ' FROM YourTable GROUP BY userId'
FROM (
  SELECT itemId 
  FROM YourTable  
  GROUP BY itemId
) 

Step 2 - run generated query

SELECT 
  userID, 
  SUM(IF(itemId = "001", rating, 0)) AS item001,
  SUM(IF(itemId = "002", rating, 0)) AS item002 
FROM YourTable 
GROUP BY userId

Result as expected

userID  item001 item002  
001     5.0     4.0  
002     4.5     3.0