日期:2014-05-17 浏览次数:20548 次
select max(case name when '课桌式' then [count] else 0 end) as 课桌式, max(case name when '分组式' then [count] else 0 end) as 分组式, .... from tb
------解决方案--------------------
create table test([name] varchar(10),[count] int) go insert test select '课桌式', 100 union all select '分组式', 360 union all select '剧院式', 200 union all select '董事会', 150 union all select 'U型', 100 union all select '宴会型', 150 select * from test declare @sql varchar(max) select @sql=isnull(@sql+',','')+' max(case when [name]='''+[name]+''' then [count] end) as '''+[name]+'''' from (select [name] from test group by [name]) t print @sql exec('select '+@sql+' from test' ) drop table test /* (6 row(s) affected) name count ---------- ----------- 课桌式 100 分组式 360 剧院式 200 董事会 150 U型 100 宴会型 150 (6 row(s) affected) U型 董事会 分组式 剧院式 课桌式 宴会型 ----------- ----------- ----------- ----------- ----------- ----------- 100 150 360 200 100 150 (1 row(s) affected) */
------解决方案--------------------
-- sql server 2000静态 select max(case name when '课桌式' then [count] else 0 end) as 课桌式, max(case name when '分组式' then [count] else 0 end) as 分组式, max(case name when '剧院式' then [count] else 0 end) as 剧院式, max(case name when '董事会' then [count] else 0 end) as 董事会, max(case name when 'U型' then [count] else 0 end) as U型 , max(case name when '宴会型'then [count] else 0 end) as 宴会型, from tab --sql server 2000动态 declare@sqlvarchar(8000) set @sql='select' select @sql=@sql+isnull(@sql+',','')+' max(case when [name]='''+[name]+''' then [count] end) as '''+[name]+'''' set @sql=@sql+'from (select [name],[count] from tab group by [name]) ' exec(@sql) --sql server 2005静态 select * from tab pivot(max(count)for name in(课桌式,分组式,剧院式,董事会,U型,宴会型)) --sql server 2005动态 declare@sqlvarchar(8000) set@sql='' --初始化变量@sql select@sql=@sql+','+[name] from tab --变量多值赋值 set@sql=stuff(@sql,1,1,'')--去掉首个',' set@sql='select * from tb pivot (max(count) for name in ('+@sql+'))a' exec(@sql)
------解决方案--------------------
select * from (select * from test_three) a pivot(max(coun) for name in(分组式,课桌式,剧院式,董事会)) b