2010-08-17 121 views
0

試圖產生一個三角矩陣乘法在T-SQL- 就像一個三角矩陣的乘法看起來就像這樣:三角矩陣乘法代

 
0 
0 1 
0 2 4 
0 3 6 9 
0 4 8 12 16 

我一直沒能找到這個有效的解決方案。任何幫助表示讚賞。

+2

請停止發送。 – 2010-08-17 19:06:45

+0

是否需要專門在SQL中完成,還是有其他選項可用? – AllenG 2010-08-17 19:07:06

+1

它的一個COBOL問題! – 2010-08-17 19:07:31

回答

4

有一個聰明的方式與XML(SQL 2005及更高版本)要做到這一點:(永久訂購數量表是一個好主意)

with Nums(n) as (
    select 0 union all 
    select 1 union all 
    select 2 union all 
    select 3 union all 
    select 4 union all 
    select 5 union all 
    select 6 union all 
    select 7 -- resize as needed or make it permanent 
) 
    select x as Prod from Nums 
    cross apply (
    select Cast(Nums.n*(N2.n) as varchar(80))+space(3-Len(Nums.n*N2.n)) 
    -- expand the varchar size if needed 
    as [text()] 
    from Nums as N2 
    where Nums.n >= n 
    order by N2.n 
    for xml path('') 
) as X(x) 
    where n <= 4 -- Adjust as needed 
    order by n; 

輸出是這樣的:

Prod 
-------- 
0 
0 1 
0 2 4 
0 3 6 9 
0 4 8 12 16