--你的结果哪儿是行转列啊,举个列子 create table tb(serial_no int,testname varchar(10))insert into tb select 1,'普通' union all select 1,'普通' union all select 3,'项目' union all select 2,'项目' select '总和' as [类型],[普通],[项目] from (select * from tb) p pivot ( sum(serial_no) for testname in([普通],[项目]) ) as pvt /* 类型 普通 项目 ---- ----------- ----------- 总和 2 5
楼主在玩 1+1 ??? 看2#,还是行转列的典型,CSDN里这类例子多的是,搜搜就知道。
use dbx; godeclare @t table( [id] int ,[year] char(4),[val] int); insert into @t select '1','2010',100 union all select '2','2010',200 union all select '2','2011',150 union all select '1','2012',1000 ; select * from @t;-- pivotselect ID, isnull([2010],0) as [2010年],isnull([2011],0) as [2011年] ,isnull([2012],0) as [2012年] from @t pivot (sum(val) for [year] in([2010],[2011],[2012])) pvt;
create table tb(serial_no int,testname varchar(10))insert into tb
select 1,'普通' union all
select 1,'普通' union all
select 3,'项目' union all
select 2,'项目' select '总和' as [类型],[普通],[项目]
from (select * from tb) p
pivot
(
sum(serial_no) for testname in([普通],[项目])
) as pvt
/*
类型 普通 项目
---- ----------- -----------
总和 2 5
楼主在玩 1+1 ???
看2#,还是行转列的典型,CSDN里这类例子多的是,搜搜就知道。
use dbx;
godeclare @t table( [id] int ,[year] char(4),[val] int);
insert into @t
select '1','2010',100 union all
select '2','2010',200 union all
select '2','2011',150 union all
select '1','2012',1000 ;
select * from @t;-- pivotselect ID, isnull([2010],0) as [2010年],isnull([2011],0) as [2011年] ,isnull([2012],0) as [2012年]
from @t
pivot (sum(val) for [year] in([2010],[2011],[2012])) pvt;