SQL server 行转换成列,case when then else end

时间:2022-08-26 10:51:44

--列转成行方式
--主要使用case when then (其实这里是创建新列,这里使用了三个case所能这里创建了三列:会计基础、计算机原理、数据结构与算法)
--详细解释:
--当表中每行记录开始时,
--查看列ctitle='会计基础'时,新的列内显示本行的score列内的值
--查看列ctitle='计算机原理'时,新的列内显示本行的score列内的值
--查看列ctitle='数据结构与算法'时,新的列内显示本行的score列内的值
select 学员姓名=s.sname,
case when ctitle='会计基础' then score end as 会计基础,
case when ctitle='计算机原理' then score end as 计算机原理,
case when ctitle='数据结构与算法' then score end as 数据结构与算法
from s
inner join sc on s.sid=sc.sid
inner join c on c.cid=sc.cid

--是面的查询已经基本实现了列变行的目的了,只是需要调整下,
--因为一个学员有一条记录就够了,现在有三条;并且每行都有空值,所以这里需要进行分组;
--可能大家注意到了,分组学员姓名就可以成为一行了,对于分值相加就可以了;
select 学员姓名=s.sname,
sum(case when ctitle='会计基础' then score end) as 会计基础,
sum(case when ctitle='计算机原理' then score end) as 计算机原理,
sum(case when ctitle='数据结构与算法' then score end )as 数据结构与算法
from s
inner join sc on s.sid=sc.sid
inner join c on c.cid=sc.cid
group by s.sname

--OK 成功!

--数据结构----------------------

--学员表
CREATE TABLE [dbo].[s](
    [sid] [int] IDENTITY(1,1) NOT NULL, --主键递增+1
    [sname] [nvarchar](50) NULL,        --学员姓名
 CONSTRAINT [PK_s] PRIMARY KEY CLUSTERED
(
    [sid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
--添加
insert into [dbo].[s](sname)values('tom');
insert into [dbo].[s](sname)values('jery');
insert into [dbo].[s](sname)values('jim');
insert into [dbo].[s](sname)values('mack');

----------------------------------------------------------
--课程表
CREATE TABLE [dbo].[c](
    [cid] [int] IDENTITY(1,1) NOT NULL, --主键递增+1
    [ctitle] [nvarchar](50) NULL,       --课程名称
 CONSTRAINT [PK_c] PRIMARY KEY CLUSTERED
(
    [cid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
insert into [dbo].[c](ctitle)values('会计基础');
insert into [dbo].[c](ctitle)values('计算机原理');
insert into [dbo].[c](ctitle)values('数据结构与算法');
-------------------------------------------------------------
--成绩表
CREATE TABLE [dbo].[sc](
    [score] [int] NULL, --成绩分数
    [cid] [int] NULL,   --课程编号
    [sid] [int] NULL    --学员编号
) ON [PRIMARY]

GO
insert into [dbo].[sc](score,cid,[sid])values(23,1,1);
insert into [dbo].[sc](score,cid,[sid])values(87,2,1);
insert into [dbo].[sc](score,cid,[sid])values(69,3,1);
insert into [dbo].[sc](score,cid,[sid])values(93,1,2);
insert into [dbo].[sc](score,cid,[sid])values(27,2,2);
insert into [dbo].[sc](score,cid,[sid])values(83,3,2);
insert into [dbo].[sc](score,cid,[sid])values(60,1,3);
insert into [dbo].[sc](score,cid,[sid])values(29,2,3);
insert into [dbo].[sc](score,cid,[sid])values(73,3,3);
insert into [dbo].[sc](score,cid,[sid])values(74,1,4);
insert into [dbo].[sc](score,cid,[sid])values(62,2,4);
insert into [dbo].[sc](score,cid,[sid])values(83,3,4);