转自:http://www.cnblogs.com/luofuxian/archive/2012/02/23/2364328.html
创建表:
CREATE TABLE [dbo].[tbl_Student]( [ID] [int] IDENTITY(1,1) NOT NULL, [学生ID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL, [学生姓名] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL, [课程ID] [nchar](10) COLLATE Chinese_PRC_CI_AS NULL, [课程名称] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL, [成绩] [int] NULL, [教师ID] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL, [教师姓名] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL ) ON [PRIMARY]
插入数据:
insert into tbl_Student values( 'S3','王五','K4 ','政治',53,'T4','赵老师'); insert into tbl_Student values( 'S1',' 张三 ','K1 ','数学',61,'T1','张老师'); insert into tbl_Student values( 'S2','李四','K3 ','英语',88,'T3','李老师'); insert into tbl_Student values( 'S1',' 张三 ','K4 ','政治',77,'T4','赵老师'); insert into tbl_Student values( 'S2','李四','K4 ','政治',67,'T5','周老师'); insert into tbl_Student values( 'S3','王五','K2 ','语文',90,'T2','王老师'); insert into tbl_Student values( 'S3','王五','K1 ','数学',55,'T1','张老师'); insert into tbl_Student values( 'S1',' 张三 ','K2 ','语文',81,'T2','王老师'); insert into tbl_Student values( 'S4','赵六','K2 ','语文',59,'T1','王老师'); insert into tbl_Student values( 'S1',' 张三 ','K3 ','英语',37,'T3','李老师'); NULL
行专列
方法1:
select 学生姓名,课程ID,成绩,教师ID,教师姓名, max(case 课程名称 when '政治' then 成绩 else 0 end) 政治, max(case 课程名称 when '语文' then 成绩 else 0 end) 语文, max(case 课程名称 when '数学' then 成绩 else 0 end) 数学, max(case 课程名称 when '英语' then 成绩 else 0 end) 英语 from tbl_Student group by 学生姓名,课程ID,成绩,教师ID,教师姓名
方法2:
select * from (select * from tbl_Student) a pivot (max(成绩) for 课程名称 in (语文,数学,英语,政治)) b
结果如图:
列转行:创建表:
CREATE TABLE [dbo].[tbl_列转行测试]( [UserID] [int] NULL, [UserNo] [int] NULL, [A] [int] NULL, [B] [int] NULL, [C] [int] NULL ) ON [PRIMARY]
插入数据:
UserID USERNo. A B C
1 1 11 22 33方法1:
SELECT USERID,USERNO,tType=attribute,value FROM (select * from tbl_列转行测试)a UNPIVOT ( value FOR attribute IN(A, B,C) ) AS UPV
结果如图: