无意中在csdn上看到一帖有关绘制杨辉三角的sql表达式,感觉很有意思。后来自己想下不借助临时表,根据杨辉三角的组合数计算方法C(n,m)=n!/[m!(n-m)!],进行绘制。
以下是完整的SQL代码:
复制代码 代码如下:
use tempdb
go
set nocount on
declare @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_1
exec(@sql)
(【注】:当前脚本在SQL Server 2012上测试通过)
效果图:
这方法虽然没有借助临时表,也有一个最大的不足就是不能设置太多行,因为在公式(C(n,m)=n!/[m!(n-m)!])中有n! 和m! 算式,设置行数太多会导致阶乘数据太大,发生数据类型转换溢出。有时间再想办法看能否从表示式中"/"除位置进行优化
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
更新日志
- 瑞鸣音乐《中国音乐地图之听见河南豫剧经典唱段》2020[WAV分轨]
- 【伊比萨沙发】VA-2024-IbizaSpring2024(LoungeCocktailsfromtheHeart)[FLAC]
- 群星《世界顶级汽车音响试音王》4K金碟16CD[WAV+CUE]
- 群星-音效环绕天碟《极致环绕人声天碟天品》7CD[WAV]
- 泰拉克SACD古典试音碟7SACD-ISO
- 群星《红歌宝典》20CD[WAV/分轨]
- 《101系列:好歌101首 细听年代精选》[WAV+CUE][3.6GB]
- 《101系列 6CD 国语经典101首歌曲 张学友 王菲代表作》[APE+CUE][2.8GB]
- 《101系列:国语经典101 VOL2 6CD 精选最经典101首》[WAV+CUE][2.3GB]
- 群星《十年网络红歌》15CD[WAV分轨]
- 宝丽金-环球10周年至50周年经典金曲15CD[低速原抓WAV+CUE]
- FIM唱片《十大男伶》[低速原抓WAV+CUE]
- 《101系列:情歌101 6CD》[WAV+CUE][3.1GB]
- 庄心妍《降调版合集》[320K/MP3][52.96MB]
- 庄心妍《降调版合集》[FLAC/分轨][118.78MB]