使用SQL將數組轉換為矩陣 ,那麼一個矩陣怎麼保存呢?
1
| 1 2 3 (ROW)
2
---+-------
3
1 | 1 2 3
4
2 | 4 5 6
5
3 | 7 8 9
6
(COL)
通常的做法是保存成一個矩陣數組如下:
01
R C V
02
---------- ---------- ----------
03
1 1 1
04
1 2 2
05
1 3 3
06
2 1 4
07
2 2 5
08
2 3 6
09
3 1 7
10
3 2 8
11
3 3 9
但是怎麼轉換回去呢?這個也很簡單,估計大學C語言教材裡就能找到例子,這裡也不多說了,那麼如何用SQL來解決這個問題呢?Thinking In Sets:
首先是Oracle的例子:
01
with array as (
02
select 1 as r, 1 as c,1 as v from dual union all
03
select 1,2,2 from dual union all
04
select 1,3,3 from dual union all
05
select 2,1,4 from dual union all
06
select 2,2,5 from dual union all
07
select 2,3,6 from dual union all
08
select 3,1,7 from dual union all
09
select 3,2,8 from dual union all
10
select 3,3,9 from dual
11
)
12
select SYS_CONNECT_BY_PATH( v, ' ') matrix
13
from array
14
where level=(select count(distinct(c)) from array)
15
start with c=1
16
connect by prior r=r
17
and prior c=c-1
18
order by r ;
1
MATRIX
2
--------
3
1 2 3
4
4 5 6
5
7 8 9
我們使用了Oracle的 connect by 進行遞歸層次查詢獲得結果:
再來看看SQL Server的例子(需要SQL Server 2005或以上版本):
01
with array as (
02
select 1 as r, 1 as c,1 as v union all
03
select 1,2,2 union all
04
select 1,3,3 union all
05
select 2,1,4 union all
06
select 2,2,5 union all
07
select 2,3,6 union all
08
select 3,1,7 union all
09
select 3,2,8 union all
10
select 3,3,9
11
),
12
cte as (
13
select 1 as lvl,r,c,cast(v as varchar(50)) as line
14
from array where c=1
15
union all
16
select lvl+1, a.r, a.c, cast(c.line+' '+cast(a.v as varchar(10)) as varchar(50))
17
from cte c, array a
18
where c.r=a.r and a.c=c.c+1
19
)
20
select line as matrix from cte
21
where lvl=(select COUNT(distinct(c)) from array)
22
order by r;
1
matrix
2
--------
3
1 2 3
4
4 5 6
5
7 8 9
SQL Server 借助CTE語法實現了遞歸層次查詢。
算法很簡單:
第一步,找出c=1的所有數據,也就是第一列上的數據
第二步,在當前數據的同一行上(Oracle:prior r=r / SQL Server:c.r=a.r)尋找下一個數據(Oracle:prior c=c-1 / SQL Server:a.c=c.c+1)
遞歸調用第二步,直到找不到下一個數據為止。