[转载]sqlserver 行转列 – 李 鹏 – 博客园.
SQLServer把行转成列在我们编码中是经常遇到的我做一个小例子大家看一下
1 --创建一个表 2 create table PayPhoneMoney 3 ( 4 id int identity(1,1), 5 userName Nvarchar(20), 6 payType nvarchar(20), 7 money decimal, 8 payTime datetime, 9 constraint pk_id primary key(id) 10 ) 11 --插入点数据 12 insert into PayPhoneMoney values('小李','支付宝',20,'2012-01-03') 13 insert into PayPhoneMoney values('小陈','工行',20,'2012-01-06') 14 insert into PayPhoneMoney values('小赵','交行',50,'2012-01-06') 15 insert into PayPhoneMoney values('小陈','支付宝',60,'2012-01-06') 16 insert into PayPhoneMoney values('小赵','工行',30,'2012-01-16') 17 insert into PayPhoneMoney values('小张','中行',30,'2012-01-16') 18 insert into PayPhoneMoney values('小李','支付宝',60,'2012-01-16')
看一下表中的数据
我们要想查一下每个人所有支付形式下的总钱数如图所示
1 -- 查一下每个人所有支付形式下的总钱数 2 select userName from PayPhoneMoney group by userName 3 select userName, 4 sum(case payType when '支付宝' then money else 0 end) as 支付宝 , 5 sum(case payType when '工行' then money else 0 end) as 工行, 6 sum(case payType when '交行' then money else 0 end) as 交行, 7 sum(case payType when '中行' then money else 0 end) as 中行 8 from PayPhoneMoney 9 group by userName
–我们这只列出了几种支付方式实际中还有很多支付方式不能一个一个都用case when 吧
–可以这样
1 declare @cmdText varchar(8000) 2 set @cmdText='select userName, ' 3 select @cmdText=@cmdText+' sum(case payType when'''+payType+'''Then money else 0 end) as '''+payType 4 +''','+char(10) from (select Distinct payType from PayPhoneMoney) T 5 print @cmdText--发现多一个逗号下面把逗号去掉 6 set @cmdText=left(@cmdText,len(@cmdText)-2)--去掉逗号 7 set @cmdText=@cmdText+'from PayPhoneMoney group by userName' 8 print @cmdText 9 exec(@cmdText)
看一下结果是一样的吧