加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

sqlserver一个动态交叉表的范例

发布时间:2020-12-12 16:01:55 所属栏目:MsSql教程 来源:网络整理
导读:社区问的人太多了,保存一个备用 -- 建立测试环境 set ?nocount? on create ? table ?test(model? varchar ( 20 ),date? int ?,qty? int ) insert ? into ?test? select ? ' a ' , ' 8 ' , ' 10 ' insert ? into ?test? select ? ' a ' , ' 10 ' , ' 50 ' in

社区问的人太多了,保存一个备用

-- 建立测试环境

set ?nocount? on

create ? table ?test(model? varchar ( 20 ),date? int ?,qty? int )

insert ? into ?test? select ? ' a ' , ' 8 ' , ' 10 '

insert ? into ?test? select ? ' a ' , ' 10 ' , ' 50 '

insert ? into ?test? select ? ' b ' , ' 100 '

insert ? into ?test? select ? ' b ' , ' 9 ' , ' 200 '

insert ? into ?test? select ? ' b ' , ' 100 '

insert ? into ?test? select ? ' c ' , ' 200 '

insert ? into ?test? select ? ' d ' , ' 300 '

insert ? into ?test? select ? ' e ' , ' 11 ' , ' 250 '

insert ? into ?test? select ? ' e ' , ' 12 ' , ' 100 '

insert ? into ?test? select ? ' f ' , ' 150 '

go

-- 测试


declare ? @sql ? varchar ( 8000 )

set ? @sql = ' select?model, '

?
select ? @sql = @sql + ' sum(case?when?date= ''' + cast (date? as ? varchar ( 10 )) + ''' ?then?qty?else?0?end)[ ' + cast (date? as ? varchar ( 10 )) + ' ], '

from ?( select ? distinct ? top ? 100 ? percent ??date

?
from ?test? order ? by ?date)a


set ? @sql ? = left ( @sql , len ( @sql ) - 1 ) + ' ?from?test?group?by?model '


exec ( @sql )


?


-- 删除测试环境

drop ? table ?test

?
set ?nocount? off


/*

model????????????????8???????????9???????????10??????????11??????????12

--------------------?-----------?-----------?-----------?-----------?-----------

a????????????????????10??????????0???????????50??????????0???????????0

b????????????????????100?????????200?????????100?????????0???????????0

c????????????????????0???????????0???????????200?????????0???????????0

d????????????????????0???????????0???????????300?????????0???????????0

e????????????????????0???????????0???????????0???????????250?????????100

f????????????????????0???????????0???????????0???????????0???????????150

*/
?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读