程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 數據庫知識 >> SqlServer數據庫 >> 關於SqlServer >> sqlserver動態交叉表的范例

sqlserver動態交叉表的范例

編輯:關於SqlServer

社區問的人太多了,保存一個備用

--建立測試環境

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','8','100'
insert into test select 'b','9','200'
insert into test select 'b','10','100'
insert into test select 'c','10','200'
insert into test select 'd','10','300'
insert into test select 'e','11','250'
insert into test select 'e','12','100'
insert into test select 'f','12','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
*/

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved