SQL 矩阵转数组

SQL Matrix to array

我正在使用 T-SQL,我有一个看起来像 Matrix (8x8) 的 table。 我的 objective 是使用 Pivot 将该矩阵 (table) 放入数组中......我已经阅读了论坛和我设法找到的更多内容,但我仍然无法为其编写代码.. .

 ID     Bucket     B1     B2     B3     B4 
 5        1        20     21     45     12
 6        2        12     18     19     48
 7        3        19     78     40     78  
 8        4        72     34     12     17

所以我需要做的就是从 table 中生成 "three dimensional array",并保存行、列和值...成为这样的东西

Row    Column   Value 
 1       1       20
 1       2       21
 1       3       45
 1       2       12
 etc
 etc
 etc
 4       3       12
 4       4       17

有人知道我如何在 T-SQL 中编写该代码吗?

ps。我这样做的原因是因为我想将矩阵与自身相乘。因此,如果我将它放在枢轴 table 中,则乘法会更容易。 谢谢

为什么要使用 PIVOT?您可以通过简单的 SELECT 查询获取数据,除非我在这里遗漏了什么?

DECLARE @Matrix TABLE (
    Id INT,
    Bucket INT,
    B1 INT,
    B2 INT,
    B3 INT,
    B4 INT);
INSERT INTO @Matrix VALUES (5, 1, 20, 21, 45, 12);
INSERT INTO @Matrix VALUES (6, 2, 12, 18, 19, 48);
INSERT INTO @Matrix VALUES (7, 3, 19, 78, 40, 78);
INSERT INTO @Matrix VALUES (8, 4, 72, 34, 12, 17);
SELECT
    Bucket AS [Row],
    1 AS [Column],
    B1 AS Value
FROM
    @Matrix
UNION ALL
SELECT
    Bucket AS [Row],
    2 AS [Column],
    B2 AS Value
FROM
    @Matrix
UNION ALL
SELECT
    Bucket AS [Row],
    3 AS [Column],
    B3 AS Value
FROM
    @Matrix
UNION ALL
SELECT
    Bucket AS [Row],
    4 AS [Column],
    B4 AS Value
FROM
    @Matrix
ORDER BY
    1, 2;

结果:

Row Column  Value
1   1   20
1   2   21
1   3   45
1   4   12
2   1   12
2   2   18
2   3   19
2   4   48
3   1   19
3   2   78
3   3   40
3   4   78
4   1   72
4   2   34
4   3   12
4   4   17

尝试逆透视您的数据:

DECLARE @table TABLE (id INT, Bucket INT, B1 INT, B2 INT, B3 INT, B4 INT)
INSERT INTO @table VALUES
(5,1,20,21,45,12),
(6,2,12,18,19,48),
(7,3,19,78,40,78),
(8,4,72,34,12,17)

SELECT rn AS [ROW],
VALUE AS [ColumnNumber],
orders AS [VALUE] 
FROM
(
SELECT ROW_NUMBER () OVER (ORDER BY id) AS rn,id, Bucket, B1 [1], B2 [2], B3 [3], B4 [4]
FROM @table
) AS t
UNPIVOT
(
    orders
    FOR VALUE IN([1], [2],[3],[4])
) AS pvt

查看此 MSDN 文档以了解 PIVOT 和 UNPIVOT 的更多详细信息。