写一条SQL语句将表一的数据转换成表二的样子
发布网友
发布时间:2022-04-10 00:18
我来回答
共4个回答
热心网友
时间:2022-04-10 01:47
这是我以前给他们做的一个行专列的例子,你可以参考一下:
/*学生表:Member
字段名称 数据类型 说明
MID Char(10) 学生号,主键
MName Char(50) 姓名
课程表Class:
字段名称 数据类型 说明
FID Char(10) 课程,主键
FName Char(50) 课程名
成绩表:Score
字段名称 数据类型 说明
SID int 自动编号,主键,成绩记录号
FID Char(10) 课程号,外键
MID Char(10) 学生号,外键
Score int 成绩*/
create table member(mid varchar(10) primary key,mname varchar(50))
create table class(fid varchar(10) primary key,fname varchar(50))
create table score(sid int primary key,fid varchar(10),mid varchar(10),score int)
go
insert into member values ('1001','张三')
insert into member values ('1002','李四')
insert into class values ('A1','数学')
insert into class values ('A2','化学')
insert into class values ('A3','*')
insert into class values ('A4','历史')
insert into class values ('A5','语文')
insert into class values ('A6','物理')
insert into score values (1,'A1','1001',80)
insert into score values (2,'A1','1002',85)
insert into score values (3,'A2','1001',84)
insert into score values (4,'A4','1002',90)
go
declare @sql varchar(8000)
select @sql='select a.mname as 学生姓名'
select @sql=@sql+',sum(case c.fname when '''+fname+''' then b.score else null end )as '+fname from class
select @sql=@sql+' from member a left join score b on a.mid=b.mid left join class c on b.fid=c.fid group by a.mname'
print @sql
exec (@sql)
热心网友
时间:2022-04-10 03:05
Create table Class([Student] nvarchar(2),[Course] nvarchar(2),[Score] int)
Insert Class
select N'张三',N'语文',78 union all
select N'张三',N'数学',87 union all
select N'张三',N'英语',82 union all
select N'张三',N'物理',90 union all
select N'李四',N'语文',65 union all
select N'李四',N'数学',77 union all
select N'李四',N'英语',65 union all
select N'李四',N'物理',85
Go
declare @s nvarchar(4000)
Select @s=isnull(@s+',','')+quotename([Course]) from Class group by[Course] --isnull(@s+',','') 去掉字符串@s中第一个逗号
exec('select [Student],'+@s+',[总成绩] from (select *,[总成绩]=sum([Score])over(partition by [Student]) from Class) a
pivot (max([Score]) for [Course] in('+@s+'))b ')
热心网友
时间:2022-04-10 04:40
select country,
sum(case type when 'A' then Money end) a,
sum(case type when 'B' then money end) b,
sum(case type when 'c' then money end) c
from test group by country order by country desc
热心网友
时间:2022-04-10 06:31
select country, sum(case when type='A' then money end) as A,
sum(case when type='B' then money end) as B,
sum(case when type='C' then money end) as C
from table1
group by country