列自動生成(交叉表 crosstab)

2021-05-21 19:19:27 字數 1556 閱讀 6537

if not object_id('today') is null

drop table today

go create table today(id int identity(1,1) primary key,inmoney int,date smalldatetime,name varchar(20))

insert into today

select 500,'2008-5-1','廠家1'

union all select 500,'2008-6-1','廠家2'

union all select 500,'2008-7-1','廠家1'

union all select 500,'2008-5-2','廠家3'

union all select 500,'2008-7-2','廠家2'

union all select 500,'2008-8-1','廠家1'

union all select 500,'2008-6-1','廠家1'

declare @col as varchar(4000),@sql varchar(8000)

set @col = ''

drop table #temp

select distinct [name] into #temp from today

select @col = @col + '[' + [name] + ']=sum(case when [name]='''

+ [name] + ''' then [inmoney] else 0 end),'

from #temp

--方法1:通過case when語法進行crosstab逐項聚合查詢

set @sql = 'select left(convert(varchar,date,20),7) 月份,' + left(@col,len(@col)-1)

set @sql = @sql + ' from today group by left(convert(varchar,date,20),7)'

execute (@sql)

--方法2(sql server 2005以上):通過pivot來實現

select @col = ''

select @col = @col + 'isnull(sum([' + [name] + ']),0) ' + [name] + ',' from #temp

set @sql = 'select left(convert(varchar,a.date,20),7) 月份,'

+ left(@col,len(@col)-1) + ' from today pivot(sum(inmoney) for name in('

select @col = ''

select @col = @col + '[' + [name] + '],' from #temp

set @sql = @sql + left(@col,len(@col)-1) + ')) as a group by left(convert(varchar,a.date,20),7)'

execute (@sql)

生成交叉表的SQL基本語句

在企業資訊化管理中,經常需要提供交叉表形式的資料給管理層。如以月份為縱軸,客戶銷售金額為橫軸。以下以sql自帶資料庫舉例列出sql語句 定義長度為8000的字串變數 msql declare msql varchar 8000 橫軸字段 select msql select month orderd...

生成交叉表的簡單通用儲存過程

if exists select from dbo.sysobjects where id object id n dbo p qry and objectproperty id,n isprocedure 1 drop procedure dbo p qry go 生成交叉表的簡單通用儲存過程 根...

生成交叉表的簡單通用儲存過程

if exists select from dbo.sysobjects where id object id n dbo p qry and objectproperty id,n isprocedure 1 drop procedure dbo p qry go 生成交叉表的簡單通用儲存過程 根...