I am working with T-SQL and I have a table that looks like Matrix (8x8).
My objective is to make that Matrix (table) into array using Pivot ... I have read forums and more stuff that i managed to find but i still can't make a code for it ...
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
So all I need to do is to make "three dimensional array" from that table, and to save row, column and value ... to be something like this
Row Column Value
1 1 20
1 2 21
1 3 45
1 2 12
etc
etc
etc
4 3 12
4 4 17
Does anyone have any idea how I could write that code in T-SQL?
ps. Reason i'm doing this, is because i want to multiply my matrix with itself. So it's easier to multiply it if i have it in pivot table.
Thank you
Try unpivoting your data :
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
Check this MSDN Doc for more details of PIVOT and UNPIVOT.
Why use PIVOT? You can get the data out with a simple SELECT query, unless I am missing something here?
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;
Results:
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