通過SQL繪製楊輝三角

來源:互聯網
上載者:User

無意中在csdn上看到一帖有關繪製楊輝三角的sql運算式,感覺很有意思。後來自己想下不藉助暫存資料表,根據楊輝三角的組合數計算方法C(n,m)=n!/[m!(n-m)!],進行繪製。

以下是完整的SQL代碼:

use tempdbgoset nocount ondeclare @rows int=10, --行數,根據實際來控制        @x int=1,@y int=1,@sql nvarchar(max),@cols int /*根據楊輝三角的組合數計算方法:C(n,m)=n!/[m!(n-m)!]進行繪製參照:http://baike.baidu.com/view/7804.htm*/ set @cols=@rows*2-1;with cte_n as(    select r from (select row_number() over(order by a.object_id) as r from sys.all_columns a ) x where r<=@rows*2),cte_1 as(select n.r,b.data_lse            from cte_n n                cross apply(select 'select '+stuff((select ',rtrim('+isnull(F1.v+'/(('+F2.v+')*'+F3.v+')','''''') +') as '+quotename(isnull(nullif((m.r +(@rows-n.r)+(m.r-1)*1)%@cols,0),@cols))                                from cte_n m                                    outer apply(select stuff((select '*'+rtrim(i.r) from cte_n i where i.r<=isnull((nullif(n.r-1,0)),1) for xml path('')),1,1,'') as v                                        ) F1                                    outer apply(select stuff((select '*'+rtrim(i.r) from cte_n i where i.r<=isnull((nullif(m.r-1,0)),1) for xml path('')),1,1,'') as v                                        ) F2                                    outer apply(select stuff((select '*'+rtrim(i.r) from cte_n i where i.r<=isnull((nullif(n.r-m.r,0)),1) for xml path('')),1,1,'') as v                                        ) F3                                where m.r<@rows*2                                order by isnull(nullif((m.r +(@rows-n.r)+(m.r-1)*1)%@cols,0),@cols) asc                                for xml path('')                                                                    ),1,1,'') as data_lse                            )b                where n.r <=@rows            )     select @sql=isnull(@sql+' union all ','')+data_lse from  cte_1exec(@sql)

(【注】當前指令碼在SQL Server 2012上測試通過

 

這方法雖然沒有藉助暫存資料表,也有一個最大的不足就是不能設定太多行,因為在公式(C(n,m)=n!/[m!(n-m)!])中有n! 和m! 算式,設定行數太多會導致階乘資料太大,發生資料類型轉換溢出。有時間再想辦法看能否從表示式中"/"除位置進行最佳化。

 

 

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.