这个问题here显示了如何将矩阵乘法转换为直线表格式,例如,给定(6x1)(路径,值)矩阵,您将获得(36,1)直线表。现在,我想获得传统的矩阵乘法格式,在示例中将是(6x6)矩阵。
如何将矩阵乘法的直线表塑造为更传统的矩阵乘法格式?
--standardSQL
WITH MatrixA AS (
SELECT 1 AS p, 2 AS val UNION ALL
SELECT 2, -3 UNION ALL
SELECT 3, 4 UNION ALL
SELECT 4, -1 UNION ALL
SELECT 5, 0 UNION ALL
SELECT 6, 2
), MatrixB AS (
SELECT 1 AS p, -1 AS val UNION ALL
SELECT 2, 2 UNION ALL
SELECT 3, 3 UNION ALL
SELECT 4, 3 UNION ALL
SELECT 5, 0 UNION ALL
SELECT 6, 1
),
matrixMultiplication AS
(
SELECT a.p AS ap, b.p as bp, SUM(a.val * b.val) val
FROM MatrixA AS a
CROSS JOIN MatrixB AS b
GROUP BY a.p, b.p
ORDER BY a.p, b.p
)
--36 elements for the 6x6 PATHS Matrix
--TODO: how to shape it to 6x6 matrix?
SELECT * FROM matrixMultiplication
答案 0 :(得分:1)
如何将其成形为6x6矩阵?
以下是BigQuery标准SQL的内容。几个简单的选项
选项1
#standardSQL
SELECT ap AS row, STRING_AGG(CAST(val AS STRING), ' ' ORDER BY bp) AS cols
FROM matrixMultiplication
GROUP BY row
-- ORDER BY row
应用于问题中的伪数据时-结果为
Row row cols
1 1 -2 4 6 6 0 2
2 2 3 -6 -9 -9 0 -3
3 3 -4 8 12 12 0 4
4 4 1 -2 -3 -3 0 -1
5 5 0 0 0 0 0 0
6 6 -2 4 6 6 0 2
选项2
#standardSQL
SELECT row,
cols[OFFSET(0)] AS col1,
cols[OFFSET(1)] AS col2,
cols[OFFSET(2)] AS col3,
cols[OFFSET(3)] AS col4,
cols[OFFSET(4)] AS col5,
cols[OFFSET(5)] AS col6
FROM (
SELECT ap AS row, ARRAY_AGG(val ORDER BY bp) AS cols
FROM matrixMultiplication
GROUP BY ap
)
-- ORDER BY row
应用于问题中的伪数据时-结果为
Row row col1 col2 col3 col4 col5 col6
1 1 -2 4 6 6 0 2
2 2 3 -6 -9 -9 0 -3
3 3 -4 8 12 12 0 4
4 4 1 -2 -3 -3 0 -1
5 5 0 0 0 0 0 0
6 6 -2 4 6 6 0 2