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