三角乘法矩阵生成

时间:2010-08-17 19:04:58

标签: sql tsql

尝试在T-SQL中生成三角乘法矩阵 像三角形乘法矩阵一样:

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

我无法为此找到有效的解决方案。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分: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;

(永久的Nums表是一个好主意。)

输出是这样的:

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