Triangular Multiplication Matrix Generation

Trying to create a triangular matrix of multiplication IN T-SQL- How the triangular matrix of multiplication will look like this:

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

I could not find an effective solution for this. Any help is appreciated.

0
source share
1 answer

A smart way to do this with XML (SQL 2005 and later):

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 persistent table is a good idea.)

Conclusion:

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

Source: https://habr.com/ru/post/1791742/


All Articles