SQL矩阵数组(SQL Matrix to array)

2019-10-23 03:25发布

我用T-SQL工作,我有一个表,看起来像矩阵(8×8)。 我的目标是让使用数据透视......我已阅读论坛和更多的东西,我设法找到了,但我仍然不能让一个代码,它是矩阵(表)到数组...

 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

因此,所有我需要做的就是让“三维阵列”从该表,并保存行,列和值......是这样的

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。 原因,我这样做,是因为我要加倍重视自己的矩阵本身。 所以它更容易繁殖,如果我在数据透视表有它。 谢谢

Answer 1:

尝试unpivoting您的数据:

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的更多细节。



Answer 2:

为什么要使用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


文章来源: SQL Matrix to array