sql行列互转

--=================行专列=======================
--if object_id('tb')is not null drop table tb
--go
--create table tb(姓名 varchar(10),课程 varchar(10),分数 int)
--insert into tb values('张三','语文',74)
--insert into tb values('张三','数学',83)
--insert into tb values('张三','物理',93)
--insert into tb values('李四','语文',74)
--insert into tb values('李四','数学',84)
--insert into tb values('李四','物理',94)
--go
--select 姓名 from tb
--select 姓名,
-- max(case when 课程='语文'then 分数 else 0 end) 语文,
-- max(case when 课程='数学'then 分数 else 0 end) 数学,
-- max(case when 课程='物理'then 分数 else 0 end) 物理,
-- sum(分数) 总分,
-- cast(avg(分数) as decimal(18,2)) 平均分
--from tb
--group by 姓名

--=====================列转行=======================
--if object_id('tb') is not null drop table tb
--go
--create table tb(姓名 varchar(10),语文 int,数学 int,物理 int)
--insert into tb values('张三',74,83,93)
--insert into tb values('李四',74,84,94)
--go
--select * from tb

--select 课程='语文'

--select * from (
-- select 姓名,课程='语文',分数=语文 from tb
-- union
-- select 姓名,课程='数学',分数=数学 from tb
-- union
-- select 姓名,课程='物理',分数=物理 from tb) newtable
-- order by 姓名,case when 课程='语文' then 1 when 课程='数学' then 2 when 课程='物理' then 3 end

原文地址:https://www.cnblogs.com/Vlaner/p/3735363.html