日期:2014-05-16 浏览次数:20768 次
Declare @sql varchar(max)
set @sql=STUFF((select ','+QUOTENAME(project) from [Table_3] group by [project] FOR XML PATH('')) ,1,1,'')
set @sql='select * from [Table_3] t
pivot (sum([price])for [project] in ('+@sql+')) a '
exec(@sql)
----------------------------------------------------------------
-- Author :fredrickhu(小F,向高手学习)
-- Date :2014-03-31 15:18:30
-- Verstion:
-- Microsoft SQL Server 2008 (RTM) - 10.0.1600.22 (Intel X86)
-- Jul 9 2008 14:43:34
-- Copyright (c) 1988-2008 Microsoft Corporation
-- Enterprise Edition on Windows NT 6.1 <X86> (Build 7601: Service Pack 1)
--
----------------------------------------------------------------
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([公司] varchar(10),[项目] varchar(4),[价格] int)
insert [tb]
select 'a','房费',10 union all
select 'a','房费',10 union all
select 'a','车费',10 union all
select 'b','车费',10 union all
select 'b','车费',10 union all
select 'b','门费',50
--------------开始查询--------------------------
declare @sql varchar(8000)
set @sql = 'select isnull(公司,''汇总'') as 公司 '
select @sql = @sql + ' , sum(case 项