--建立测试环境 set nocount on createtable test(model varchar(20),date int ,qty int) insertinto test select'a','8','10' insertinto test select'a','10','50' insertinto test select'b','8','100' insertinto test select'b','9','200' insertinto test select'b','10','100' insertinto test select'c','10','200' insertinto test select'd','10','300' insertinto test select'e','11','250' insertinto test select'e','12','100' insertinto test select'f','12','150' go --测试 declare@sqlvarchar(8000) set@sql='select model,' select@sql=@sql+'sum(case when date='''+cast(date asvarchar(10))+''' then qty else 0 end)['+cast(date asvarchar(10))+'],' from (selectdistincttop100percent date from test orderby date)a set@sql=left(@sql,len(@sql)-1)+' from test group by model' exec(@sql) --删除测试环境 droptable 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 */